反序列化JSON Swift 4.2

时间:2019-04-18 16:22:50

标签: json swift

我尝试使用Decodable协议反序列化JSON,我也将CoumKey与enum一起使用,但它不起作用。我只需要嵌套数组(以“ indicator”开头),并且只需几个字段(它们都在struct中)。我尝试了很多不同的选择,但不幸的是。 附言我也尝试没有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()

1 个答案:

答案 0 :(得分:0)

创建根结构并使用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进行两次序列化非常昂贵。