I’m working with a COVID-19 data API and having trouble decoding nested arrays in Swift. The API returns data that looks like this:
[
{
"country": "USA",
"states": [
{
"state": "California",
"cases": 1250,
"deaths": 15,
"recovered": 200,
"active": 1035
}
],
"lat": 37.0902,
"lng": -95.7129,
"updated": "2020-04-01"
}
]
I created these data models:
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 weird thing is that JSON parsing only works when I remove the nested array:
struct CountryData: Codable {
let country: String
// let states: [StateInfo] // commenting this out makes it work
}
Here’s my parsing code:
override func viewDidLoad() {
super.viewDidLoad()
APIManager.shared.fetchData(url: "api-endpoint", apiKey: "abc123") { responseData in
guard let responseData = responseData else { return }
do {
let countries = try JSONDecoder().decode([CountryData].self, from: responseData)
let firstState = countries[0].states[0].state
self.stateName = firstState
DispatchQueue.main.async {
print(self.stateName)
}
} catch {
print("Decoding failed: \(error)")
}
}
}
What could be wrong with my model structure? The parsing fails whenever I include the nested array property.