有谁能告诉我我做错了什么?
这是我试图解析的JSON:
{
"results": {
"AF": {
"alpha3": "AFG",
"currencyId": "AFN",
"currencyName": "Afghan afghani",
"currencySymbol": "؋",
"id": "AF",
"name": "Afghanistan"
},
"AI": {
"alpha3": "AIA",
"currencyId": "XCD",
"currencyName": "East Caribbean dollar",
"currencySymbol": "$",
"id": "AI",
"name": "Anguilla"
}
}
}
我的代码:
class Results: Codable {
let results: [Country]
init(results: [Country]) {
self.results = results
}
}
class Country: Codable {
let currencyId: String
let currencyName: String
let currencySymbol: String
let id: String
let name: String
init(currencyId :String, currencyName: String, currencySymbol: String, id: String, name: String ) {
self.currencyId = currencyId
self.currencyName = currencyName
self.currencySymbol = currencySymbol
self.id = id
self.name = name
}
}
我看过Apple解码嵌套结构的文档,但我仍然不明白如何正确地处理不同级别的JSON。
感谢。
答案 0 :(得分:1)
检查键"results"
的概述值。
"results": {
...
}
{...}
表示JSON对象。如果你认为它更好,Swift struct
(或class
在某些情况下适用于JSON对象。
在其他情况下,Swift Dictionary
可能更合适。
此JSON对象的每个值都采用以下形式:
{
"alpha3": ...,
"currencyId": ...,
"currencyName": ...,
"currencySymbol": ...,
"id": ...,
"name": ...
}
与您的Country
匹配。
因此,您只需更改results
课程中Results
的类型。
class Results: Codable {
let results: [String: Country]
init(results: [String: Country]) {
self.results = results
}
}
对于属性及其类具有相同的名称(没有大小写)可能会在将来引起一些混淆,但我保持原样。
你可以这样测试:
(假设在Playground中使用修改后的Results
和您的Country
进行测试。)
let jsonText = """
{
"results": {
"AF": {
"alpha3": "AFG",
"currencyId": "AFN",
"currencyName": "Afghan afghani",
"currencySymbol": "؋",
"id": "AF",
"name": "Afghanistan"
},
"AI": {
"alpha3": "AIA",
"currencyId": "XCD",
"currencyName": "East Caribbean dollar",
"currencySymbol": "$",
"id": "AI",
"name": "Anguilla"
}
}
}
"""
let jsonData = jsonText.data(using: .utf8)!
let decoder = JSONDecoder()
do {
let results = try decoder.decode(Results.self, from: jsonData)
print(results) //-> __lldb_expr_1.Results
} catch {
print(error)
}