I’m working with a COVID-19 API that returns nested JSON data. When I try to decode the full structure including nested arrays, it fails, but works fine when I only decode the top level fields.
Here’s the JSON response I’m getting:
[{
"country": "USA",
"states": [
{
"state": "California",
"cases": 1250,
"deaths": 45,
"recovered": 200,
"active": 1005
}
],
"lat": 39.8283,
"lng": -98.5795,
"lastUpdate": "2020-04-02"
}]
I created these models to parse the data:
struct CountryData: Codable {
let country: String
let states: [StateInfo]
}
struct StateInfo: Codable {
let state: String
let cases: Int
let deaths: Int
let recovered: Int
let active: Int
}
The parsing works when I remove the states array from my model, but fails when I include it. Here’s my parsing code:
func loadData() {
APIManager.shared.fetchData(endpoint: "covid-data", apiKey: "abc123") { result in
guard let result = result else { return }
do {
let countries = try JSONDecoder().decode([CountryData].self, from: result)
let firstState = countries[0].states[0].state
self.stateName = firstState
DispatchQueue.main.async {
print(self.stateName)
}
} catch {
print("Decoding failed: \(error)")
}
}
}
What could be causing the nested array parsing to fail? The structure looks correct to me but I must be missing something.