Search code examples
jsonswiftalamofire

(Swift) How to parse JSON response that sometimes contains a certain field?


I am trying to parse a JSON response that sometimes contains a field 'state' and sometimes does not. For example:

{
country: "US", 
lat: 69, 
lon: 69, 
name: "CityName",
state: "StateName"
}

vs.

{
country: "US", 
lat: 69, 
lon: 69, 
name: "CityName"
}

I am using Alamofire to parse it as such, but of course run into errors when the json response does not contain the 'state' field.

      AF.request("API.COM").responseData(completionHandler: { response in
            guard let data = response.data else { return }
            let responses = try! JSONDecoder().decode([apiResponse].self, from: data)
            print(responses as Any)
            self.dispatchGroup.leave()
        })

Where:

struct apiResponse: Decodable {
    var country: String
    var lat: Float
    var lon: Float
    var name: String
    var state: String
}

I would like to get a struct for each object in the response, whether or not it contains the 'state' field. What is the best way to do this? I tried using some do/catch logic to catch an error when parsing an object and then try to parse it with a decodable struct that didnt have the state field, but that didnt work out for me. Thank you so much in advance for any help.


Solution

  • Use an Optional for the optional property, that's what they're intended for. I.e,

    var state: String?
    

    Also, a couple of unrelated hints:

    • you can likely change all the vars in your struct to lets
    • rename it as ApiResponse (capital A) - types in Swift usually start with capital letters.
    • look into using URLSession and Codable instead of adding thousands and thousands of lines of code from an external library.