Reputation: 11143
I'm practicing my Swift skills, this time I'm trying to make a Covid-19 tracker, and for this I found this API, the thing is, that the format retrieved by /cases
is something like this (changing keys to make it more readable)
{
"Country1": {
"All": {
"property1": 0,
"property2": "foo"
}
}, {
"All": {
"property1": "0",
"property2": "bar",
},
"State1": {
"property1": 0,
"property3": "foobar"
}
}
}
And I made the following structs to decode it:
Country
struct Country: Codable {
let All: [String: All]
private enum CodingKeys: String, CodingKey {
case All
}
}
All
struct All: Codable {
let confirmed: Int?
let recovered: Int?
let deaths: Int?
let country: String?
let population: Int?
let squareKmArea: Int?
let lifeExpectancy: String?
var elevationInMeters: String?
let continent: String?
let location: String?
let iso: String?
let capitalCity: String?
let lat: String?
let long: String?
let updated: String?
private enum CodingKeys: String, CodingKey {
case confirmed
case recovered
case deaths
case country
case population
case squareKmArea = "sq_km_area"
case lifeExpectancy = "life_expectancy"
case elevationInMeters = "elevation_in_meters"
case continent
case location
case iso
case capitalCity = "capital_city"
case lat
case long
case updated
}
init(confirmed: Int?, recovered: Int?, deaths: Int?, country: String?, population: Int?,
squareKmArea: Int?, lifeExpectancy: String?, elevationInMeters: String?,
continent: String?, location: String?, iso: String?, capitalCity: String?,
lat: String?, long: String?, updated: String?) {
self.confirmed = confirmed
self.recovered = recovered
self.deaths = deaths
self.country = country
self.population = population
self.squareKmArea = squareKmArea
self.lifeExpectancy = lifeExpectancy
self.elevationInMeters = elevationInMeters
self.continent = continent
self.location = location
self.iso = iso
self.capitalCity = capitalCity
self.lat = lat
self.long = long
self.updated = updated
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.confirmed = try container.decodeIfPresent(Int.self, forKey: .confirmed)
self.recovered = try container.decodeIfPresent(Int.self, forKey: .recovered)
self.deaths = try container.decodeIfPresent(Int.self, forKey: .deaths)
self.country = try container.decodeIfPresent(String.self, forKey: .country)
self.population = try container.decodeIfPresent(Int.self, forKey: .population)
self.squareKmArea = try container.decodeIfPresent(Int.self, forKey: .squareKmArea)
self.lifeExpectancy = try container.decodeIfPresent(String.self, forKey: .lifeExpectancy)
self.elevationInMeters = try container.decodeIfPresent(String.self, forKey: .elevationInMeters)
self.continent = try container.decodeIfPresent(String.self, forKey: .continent)
self.location = try container.decodeIfPresent(String.self, forKey: .location)
self.iso = try container.decodeIfPresent(String.self, forKey: .iso)
self.capitalCity = try container.decodeIfPresent(String.self, forKey: .capitalCity)
self.lat = try container.decodeIfPresent(String.self, forKey: .lat)
self.long = try container.decodeIfPresent(String.self, forKey: .long)
self.updated = try container.decodeIfPresent(String.self, forKey: .updated)
do {
self.elevationInMeters = try String(container.decodeIfPresent(Int.self, forKey: .elevationInMeters) ?? 0)
} catch DecodingError.typeMismatch {
print("Not a number")
self.elevationInMeters = try container.decodeIfPresent(String.self, forKey: .elevationInMeters) ?? ""
}
}
}
The elevation in meters can come in either String or Int value (4+ digits long > String (appends a comma), otherwise Int) (Idea taken from this answer
And I try to decode it this way
if let decodedData = self.jsonUtilities.decode(json: safeData, as: [String : Country].self) {
print(decodedData)
}
My above decode
method looks like this:
func decode<T: Decodable>(json: Data, as clazz: T.Type) -> T? {
do {
let decoder = JSONDecoder()
let data = try decoder.decode(T.self, from: json)
return data
} catch {
print(error)
print("An error occurred while parsing JSON")
}
return nil
}
I found this answer where they suggest adding all the Coding Keys there, but these are a ton.
I haven't added all the keys, as it's an 8k+ lines JSON, so I was wondering if there's an easier way to decode it, as I can't think of a better way to decode this JSON with unique keys.
Alternatively if I could ignore all the keys that aren't "All"
might also work, as I'm just trying to get the totals per country and their locations to place them in a map.
So far I get this error:
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Diamond Princess", intValue: nil), CodingKeys(stringValue: "All", intValue: nil), _JSONKey(stringValue: "recovered", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
An error occurred while parsing JSON
And afaik it's because it's not finding the key "Diamond Princess" which is a state (or so I believe) in Canada (according to my JSON), because I haven't added it for the reasons above.
Upvotes: 0
Views: 1870
Reputation: 49590
When you have dynamic keys, you could decode it as [String: ...]
dictionary.
The structure of the JSON is as follows:
{
"Canada": {
"All": { ... },
"Ontario": { ... },
...
},
"Mexico": { ... },
...
}
All the country stats have the key "All"
and if that's all you need then you could create the following structs:
struct Country: Decodable {
var all: CountryAll
enum CodingKeys: String, CodingKey {
case all = "All"
}
}
struct CountryAll: Decodable {
var confirmed: Int
var recovered: Int
//.. etc
}
and decode as:
let countries = try JSONDecoder().decode([String: Country].self, from: json)
Upvotes: 2