Skip to content Skip to sidebar Skip to footer

The Data Couldn't Be Read Because It Is Missing

SOLVED: The data couldn't exist read because it isn't in the right format.

Forums > SwiftUI

@iam-that-1

this is the API

                        {    "ip":"",    "hostname":"",    "continent_code":"",    "continent_name":"",    "country_code2":"",    "country_code3":"",    "country_name":" ",    "country_capital":"",    "state_prov":"",    "district":"",    "city":"",    "zipcode":"",    "latitude":00.00,    "longitude":00.00,    "is_eu":"false",    "calling_code":"+",    "country_tld":"",    "languages":"",    "country_flag":"https",    "internet service provider":"",    "connection_type":"",    "organization":"",    "asn":"",    "geoname_id":0000,    "currency":{       "name":"",       "code":"",       "symbol":""    },    "time_zone":{       "proper noun":"",       "offset":3,       "current_time":"",       "current_time_unix":"",       "is_dst":"",       "dst_savings":0    } }                      

and this is structs

                        struct Location: Codable {     allow ip, hostname, continentCode, continentName: String?     let countryCode2, countryCode3, countryName, countryCapital: String?     let stateProv, district, city, zipcode: String?     let latitude, longitude: Double?     permit isEu, callingCode, countryTLD, languages: String?     let countryFlag: Cord?     let internet access provider, connectionType, organization, asn: String?     let geonameID: Int?     let currency: Currency?     allow timeZone: TimeZone?      enum CodingKeys: String, CodingKey {         case ip, hostname         case continentCode         case continentName         case countryCode2         case countryCode3         case countryName         case countryCapital         example stateProv         instance commune, urban center, zipcode, breadth, longitude         case isEu         case callingCode         case countryTLD         instance languages         example countryFlag         case isp         case connectionType         case organisation, asn         case geonameID         example currency         case timeZone     } }  struct Currency: Codable {     let name, code, symbol: String? }  struct TimeZone: Codable {     permit name: String?     let offset: Int?     let currentTime, currentTimeUnix, isDst: String?     let dstSavings: Int?      enum CodingKeys: String, CodingKey {         instance name, offset         case currentTime         case currentTimeUnix         case isDst         example dstSavings     } }                                              

just I got this error. (The data couldn't be read because it isn't in the correct format.).

I built the structs from a script

1

@roosterboy HWS+

Is that the actual JSON yous are testing with or did y'all give united states an altered version? Because information technology'due south not valid JSON due to these lines:

                                                  "latitude":00.00,    "longitude":00.00,     "geoname_id":0000,                      

They should be:

                                                  "latitude":0.0,    "longitude":0.0,     "geoname_id":0,                      

i

@iam-that-one

yea it is altered, becuase the response contains my information. just I want to know if the structs stand for the json structure or not, and how to do it. The actual JSON is valid and contains an actual breadth and longitude.

asking function:

                                                  func fetch_location(API_KEY : Cord, ip : String){         let API_URL = "https://api.ipgeolocation.io/ipgeo?apiKey=\(API_KEY)&ip=\(ip)"         baby-sit allow url = URL(string: API_URL)else{             print("invalid url ...")             return         }         let decoder = JSONDecoder()         permit request = URLRequest(url: url)          URLSession.shared.dataTask(with: asking) { (data, response, error) in             if error != nil{                 print("fault i")                 impress(error?.localizedDescription equally Whatever)             }             else{                 if let data = data{                     do{                     let result = effort decoder.decode(Location.cocky, from: data)                         impress(effect )                      }catch{                         print("errpr 2")                         print(mistake.localizedDescription)                     }                 }             }         }.resume()     }                      

1

@roosterboy HWS+

just I want to know if the structs represent the json structure or not

Aye. Once I corrected the zeroes event, your structsouthward worked fine to decode the example JSON.

A tip...

When decoding JSON, don't do this:

                        impress(error.localizedDescription)                      

Do this instead:

                        print(fault)                      

Information technology will give you much more than particular about what the problem is.

This:

                        The data couldn't be read because it isn't in the right format.                      

versus this:

                        dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was non valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Lawmaking=3840 "Number with leading zero effectually character 482."                      

i

@iam-that-ane

I got the problem when I print(error), I inverse latitude, longitude to be String instade of Double, thankyou.

ane

@iam-that-one

I am sorry. just why some properties contains zero inside. The API has a value.

1

@roosterboy HWS+

Okay, after hunting down some sample API information—which you actually should supply with these types of questions, as your structs worked fine with the sample information you did provide but fail with actual sample data from the API documentation—y'all can brand these changes and it should piece of work:

                        struct Location: Codable {     let ip, hostname, continentCode, continentName: String?     let countryCode2, countryCode3, countryName, countryCapital: String?     let stateProv, district, city, zipcode: String?     let breadth, longitude: String? //instead of Double?     let isEu: Bool?  //instead of String?     permit callingCode, countryTld, languages: String? //countryTld instead of countryTLD     let countryFlag: String?     let isp, connectionType, organization, asn: Cord?     let geonameId: Cord? //instead of permit geonameID: Int?     let currency: Currency?     allow timeZone: TimeZone?      enum CodingKeys: String, CodingKey {         case ip, hostname         example continentCode         case continentName         case countryCode2         case countryCode3         case countryName         case countryCapital         case stateProv         instance district, urban center, zipcode, breadth, longitude         case isEu         instance callingCode         case countryTld //instead of countryTLD         case languages         example countryFlag         instance isp         example connectionType         case organization, asn         case geonameId //instead of geonameID         case currency         instance timeZone     } }  //no changes to Currency struct  struct TimeZone: Codable {     allow name: String?     permit offset: Int?     allow currentTime: String?     let currentTimeUnix: Appointment? //instead of Cord?     let isDst: Bool? //instead of Cord?     allow dstSavings: Int?      enum CodingKeys: Cord, CodingKey {         case name, start         case currentTime         case currentTimeUnix         example isDst         case dstSavings     } }                      

And and then when yous create your JSONDecoder, be sure to ready its keyDecodingStrategy to .convertFromSnakeCase.

OR, you can add explicit key mappings to your CodingKeys enums, like this:

                        example continentCode = "continent_code" example continentName = "continent_name" //...etc..                      

Note that doing it this mode would allow you lot to keep countryTLD and geonameID in your Location struct.

                        case countryTLD = "country_tld" example geonameID = "geoname_id"                      

1

@iam-that-i

Thank you, it was my mistake, I merely took sampel of resopnses that is non workes in my case, or non represents the bodily response from API.

1

Sponsor Hacking with Swift and reach the earth's largest Swift customs!

Answer to this topic…

You lot demand to create an account or log in to respond.

All interactions here are governed by our code of comport.

murphypoette.blogspot.com

Source: https://www.hackingwithswift.com/forums/swiftui/the-data-couldn-t-be-read-because-it-isn-t-in-the-correct-format/7440

إرسال تعليق for "The Data Couldn't Be Read Because It Is Missing"