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.
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:
var
s in your struct to let
sApiResponse
(capital A) - types in Swift
usually start with capital letters.URLSession
and Codable
instead of adding thousands and thousands of lines of code from an external library.