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
[
{
"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
// ...
}