如何使用Codable协议使用自定义参数解析JSON

时间:2018-05-31 12:42:13

标签: json swift codable decodable

我有 JSON ,带有键

{  
   "yearOfManufacture":"20/9/2018",
   "carSize":8,
   "isNew":true,
   "carAssets":[  
      {  
         "color":"5761807993001",
         "nativeId":"{\"app\":\"1234/Car/Native_App\",\"web\":\" /8888/Car/Native_Car_Desktop\"}"
      }
   ]
}

我正在尝试使用 Codable 协议解析结构模型

struct Cars: Codable {
   var yearOfManufacture: String?
   var carSize: Int = 0
   var isNew: Bool = true
   var carAssets: [CarAssests]?
}

struct CarAssests: Codable { 
   var color: String?
   var nativeId: String?
}

我收到错误,如数据无法读取,因为格式不正确。我尝试使用CodingKeys与解码器容器无法获得“nativeId的确切类型“:”{\“app \”:\“1234 / Car / Native_App \”,\“web \”:\“/ 8888 / Car / Native_Car_Desktop \”}“未获得此类型的确切数据类型。

let decoder = JSONDecoder()
        decoder.dataDecodingStrategy = .deferredToData
        if let jsonData = jsonString.data(using: .utf8) {
            do {

                print(jsonData)
                let assets = try decoder.decode(Cars.self, from: jsonData)
                print(assets)
            } catch {
                print(error.localizedDescription)
            }
        }

1 个答案:

答案 0 :(得分:0)

我打赌你做的是这样的事情:

let jsonString = """
{
"yearOfManufacture": "20/9/2018",
"carSize": 8,
"isNew": true,
"carAssets": [
{
"color": "5761807993001",
"nativeId": "{\"app\":\"1234/Car/Native_App\",\"web\":\" /8888/Car/Native_Car_Desktop\"}"
}
]
}
"""

在多行字符串中,\""均表示字符"。所以你必须写\\"来获得两个字符\"

let jsonString = """
{
"yearOfManufacture": "20/9/2018",
"carSize": 8,
"isNew": true,
"carAssets": [
{
"color": "5761807993001",
"nativeId": "{\\"app\\":\\"1234/Car/Native_App\\",\\"web\\":\\" /8888/Car/Native_Car_Desktop\\"}"
}
]
}
"""