谁能告诉我我做错了什么?
这是我试图解析的 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。
谢谢。
检查 key 的轮廓值"results"
。
"results": {
...
}
{...}
表示 JSON 对象。在某些情况下,Swift struct
(或者class
如果您认为它更好)适用于 JSON 对象。
在其他情况下,SwiftDictionary
可能更合适。
这个 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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句