Please look closely at the JSON, the values for keys newDeathsByDeathDate
and cumDeathsByDeathDate
can be null
.
Make the type of the corresponding struct members optional
struct MyData: Codable{
let date: String
let areaName: String
let areaCode: String
let newCasesByPublishDate: Int
let cumCasesByPublishDate: Int?
let newDeathsByDeathDate: Int?
let cumDeathsByDeathDate: Int?
}
Alternatively – to keep non-optional values – decode the JSON manually and set the values to 0 if they are null
struct MyData : Decodable {
let date, areaName, areaCode: String
let newCasesByPublishDate, cumCasesByPublishDate : Int
let newDeathsByDeathDate, cumDeathsByDeathDate: Int
private enum CodingKeys : String, CodingKey { case date, areaName, areaCode, newCasesByPublishDate, cumCasesByPublishDate, newDeathsByDeathDate, cumDeathsByDeathDate }
init(from decoder : Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
date = try container.decode(String.self, forKey: .date)
areaName = try container.decode(String.self, forKey: .areaName)
areaCode = try container.decode(String.self, forKey: .areaCode)
newCasesByPublishDate = (try? container.decode(Int.self, forKey: .newCasesByPublishDate)) ?? 0
cumCasesByPublishDate = (try? container.decode(Int.self, forKey: .cumCasesByPublishDate)) ?? 0
newDeathsByDeathDate = (try? container.decode(Int.self, forKey: .newDeathsByDeathDate)) ?? 0
cumDeathsByDeathDate = (try? container.decode(Int.self, forKey: .cumDeathsByDeathDate)) ?? 0
}
}
And again, don't ignore useful error messages by printing something meaningless
Replace
print("Something Went Wrong")
with
print("An error occured:", error!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…