Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift – How to decode a JSON path that looks like this 0.lat

I would like to get the position data of a city from the openweathermap Geocoding API
But I have a problem with there Json struct and that the path starts with a 0

like this: 0.lat

here is an example of the JSON I get back

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "name": "Osimo",
    "local_names": {
      "ru": "Озимо",
      "fr": "Osime",
      "it": "Osimo"
    },
    "lat": 43.4861359,
    "lon": 13.4824068,
    "country": "IT",
    "state": "Marche"
  }
]

And this is my code. I found CodingKey when I was looking up the problem but it doesn’t work in my code or I did made a mistake.

PositionData.swift

enum CodingKeys: String, CodingKey {
    case zero = "0"
}
struct PositionData: Decodable {
        let zer0: Zero
    }

struct Zero: Decodable {

But when I would like to code the path it tells me that: Value of type ‘PositionData’ has no member ‘0’

LocationManager.Swift

do {
            let decodedData = try decoder.decode(PositionData.self, from: positionData)
            print(decodedData.0.lat)
        } catch {
            print("Error in Json")

I tried to load the position data of the openweathermap Geocoding API.
Now I am not sure how to decode the JSON data with a path like this 0.lat

>Solution :

There is no the path starts with a 0.

You have to decode an array and get the item at index zero

do {
    let decodedData = try decoder.decode([PositionData].self, from: positionData)
     print(decodedData[0].lat)  // better print(decodedData.first?.lat)
} catch {
    print(error) // NEVER print a literal like ("Error in Json")
}

and delete

enum CodingKeys: String, CodingKey {
    case zero = "0"
}
struct PositionData: Decodable {
        let zer0: Zero
    }

struct Zero: Decodable {

PositionData must look like

struct PositionData: Decodable {
    let lat, lon: Double
    // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading