如何使用可编码协议使用自定义参数解析 JSON



我有一个带键的JSON

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

我正在尝试使用带有结构模型的可编码协议进行解析

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)
}
}

我敢打赌你正在做这样的事情:

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\"}"
}
]
}
"""

相关内容

  • 没有找到相关文章

最新更新