我认为我正确创建了结构,但它给出了错误。
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期解码数组,但找到了字典。”,underlyingError:nil))
型号:
struct veriler : Codable {
let success : Bool
let result : [result]
}
struct result : Codable {
let country : String
let totalCases : String
let newCases : String
let totalDeaths : String
let newDeaths : String
let totalRecovered : String
let activeCases : String
}
JSON 数据:
{
"success": true,
"result": [
{
"country": "China",
"totalcases": "80,881",
"newCases": "+21",
"totaldeaths": "3,226",
"newDeaths": "+13",
"totalRecovered": "68,709",
"activeCases": "8,946"
},
{
"country": "Italy",
"totalcases": "27,980",
"newCases": "",
"totaldeaths": "2,158",
"newDeaths": "",
"totalRecovered": "2,749",
"activeCases": "23,073"
},
"..."
]
}
解码:
let decoder = JSONDecoder()
do {
let country = try decoder.decode([result].self, from: data!)
for i in 0..<country.count {
print (country[i].country)
}
} catch {
print(error)
}
首先,您需要通过指定自定义
result
来修改您的 CodingKeys
结构(请注意模型中的 totalCases
与 JSON 中的 totalcases
之间的不匹配):
struct result: Codable {
enum CodingKeys: String, CodingKey {
case country, newCases, newDeaths, totalRecovered, activeCases
case totalCases = "totalcases"
case totalDeaths = "totaldeaths"
}
let country: String
let totalCases: String
let newCases: String
let totalDeaths: String
let newDeaths: String
let totalRecovered: String
let activeCases: String
}
然后你需要解码
veriler.self
而不是[result].self
:
let decoder = JSONDecoder()
do {
let result = try decoder.decode(veriler.self, from: data!)
let countries = result.result
for i in 0 ..< countries.count {
print(countries[i].country)
}
} catch {
print(error)
}
注意:我建议遵循 Swift 指南并命名结构,如
Result
或 Veriler
(仅实例应为小写)。