【发布时间】:2019-09-09 00:49:58
【问题描述】:
我尝试使用 Decodable 协议反序列化我的 JSON,我也将 enum 与 CodingKey 一起使用,但它不起作用。我只需要嵌套数组(以“indicator”开头),并且只需要几个字段(所有字段都在结构中)。我尝试了很多不同的选择,但不幸的是.. 附:我也尝试在没有 CodingKey 的情况下做到这一点。无论如何响应是:“Swift.DecodingError.keyNotFound(CodingKeys(stringValue:“country”,intValue:nil)”我读到这个,也许数组是一个原因(我的意思是这个奇怪的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()
【问题讨论】:
-
解码前需要修改响应结果。当您只需要该任意数组中的第二个对象时,您正试图将任意数组解码为
CountryObject数组。 -
没有我想要的那么简单,但是没关系。谢谢。