gpt4 book ai didi

json - 反序列化 JSON swift 4.2

转载 作者:行者123 更新时间:2023-11-30 10:46:04 30 4
gpt4 key购买 nike

我尝试使用 Decodable 协议(protocol)反序列化我的 JSON,我还使用带有 CodingKey 的枚举,但它不起作用。我只需要嵌套数组(以“指示器”开头),并且只需要几个字段(所有字段都在结构中)。我尝试了很多不同的选择,但不幸的是..附:我也尝试在没有 CodingKey 的情况下做到这一点。无论如何,响应是:“Swift.DecodingError.keyNotFound(CodingKeys(stringValue:“country”,intValue:nil)”Ofc我读到了这篇文章,也许数组是一个原因(我的意思是这个奇怪的intValue)?

JSON

[  
{
"page":1,
"pages":2,
"per_page":50,
"total":59,
"sourceid":"2",
"lastupdated":"2019-03-21"
},
[
{
"indicator":{
"id":"IP.PAT.RESD",
"value":"Patent applications, residents"
},
"country":{
"id":"SS",
"value":"South Sudan"
},
"countryiso3code":"SSD",
"date":"2018",
"value":null,
"unit":"",
"obs_status":"",
"decimal":0
},
{
"indicator":{
"id":"IP.PAT.RESD",
"value":"Patent applications, residents"
},
"country":{
"id":"SS",
"value":"South Sudan"
},
"countryiso3code":"SSD",
"date":"2017",
"value":null,
"unit":"",
"obs_status":"",
"decimal":0
},
...
]
]

我的代码

struct CountryObject: Decodable{
var country: CountryInfo
var date: Int
var value: Int?
private enum RawValues: String, Decodable{
case date = "date"
case vallue = "value"
}
}
struct CountryInfo: Decodable{//Country names
var id: String?
var value: String?
private enum RawValues: String, Decodable{
case id = "id"
case value = "value"
}
}//
let urlString = "https://api.worldbank.org/v2/country/SS/indicator/IP.PAT.RESD?format=json"
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) {(data,response,error) in
guard let data = data else {return}
guard error == nil else {return}
do{
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let countryObject = try! decoder.decode([CountryObject].self, from: data)
print(countryObject)
}catch let error{
print(error)
}
}.resume()

最佳答案

创建根结构并使用 unkeyedContainer 解码数组

struct Root : Decodable {

let info : Info
let countryObjects : [CountryObject]

init(from decoder: Decoder) throws {
var arrayContrainer = try decoder.unkeyedContainer()
info = try arrayContrainer.decode(Info.self)
countryObject = try arrayContrainer.decode([CountryObject].self)
}
}

struct Info : Decodable {
let page, pages, perPage: Int
let lastupdated: String
}

struct CountryObject : Decodable {
let country: CountryInfo
let date: String
let value: Int?
}

struct CountryInfo : Decodable { //Country names
let id: String
let value: String
}

...

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let root = try decoder.decode(Root.self, from: data)
let countryObjects = root.countryObjects
print(countryObjects)
} catch { print(error) }

两次(反)序列化 JSON 的成本是不必要的。

关于json - 反序列化 JSON swift 4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750155/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com