Swift JSON Decoding Issue with Nested Array Objects in API Response

I’m working with a COVID-19 data API and running into problems when trying to decode nested arrays. The API returns data that looks like this:

[
  {
    "country": "United States",
    "states": [
      {
        "state": "California",
        "cases": 1250,
        "cured": 45,
        "fatalities": 12,
        "current": 1193
      }
    ],
    "lat": 39.8283,
    "lng": -98.5795,
    "timestamp": "2020-04-15"
  }
]

I created these data models:

struct Nation: Codable {
    let country: String
    let states: [State]
}

struct State: Codable {
    let state: String
    let cases: Int
    let cured: Int
    let fatalities: Int
    let current: Int
}

The weird thing is that JSON parsing only works when I remove the nested array property:

struct Nation: Codable {
    let country: String
    // let states: [State]  // commenting this out makes it work
}

Here’s my parsing code:

override func viewDidLoad() {
    super.viewDidLoad()
    
    APIService.shared.fetchData(endpoint: "covid-data", apiKey: "abc123") { responseData in
        guard let responseData = responseData else { return }
        
        do {
            let nations = try JSONDecoder().decode([Nation].self, from: responseData)
            let firstState = nations[0].states[0].state
            self.selectedState = firstState
            
            DispatchQueue.main.async {
                print(self.selectedState)
            }
        } catch {
            print("Decoding failed: \(error)")
        }
    }
}

What could be causing this issue with the nested array decoding?

ya, ur JSON struct might not match the API respnse. try printing the raw data 1st to see the actual format - sometimes APIs wrap things in extra objs or have dif arr structures. also, make sure your Codable props match the JSON keys exactly, even cap.

Your Nation struct is missing properties. The API returns lat, lng, and timestamp fields that aren’t in your model. When JSONDecoder hits these extra fields, it chokes and fails to decode everything - including your nested states array.

Add the missing properties to your Nation struct:

struct Nation: Codable {
    let country: String
    let states: [State]
    let lat: Double
    let lng: Double
    let timestamp: String
}

I’ve hit this same wall with third-party APIs. The decoder won’t budge unless every JSON field has a match (or you write custom decoding). Once you add all the response properties, your nested array should work fine.

I ran into this exact problem last month with a weather API. It’s not missing properties - JSONDecoder handles extra fields fine by default. You’ve probably got null or missing values in the states array, or the states array itself is null for some countries. Make your states property optional first: let states: [State]?. Also check if any integer fields in your State struct could be coming through as null from the API. Adding optional types for potentially missing data fixed my similar decoding failures. You can safely unwrap them later in your code.