[英]Decoding this kind of JSON with Codable
我有一个看起来像这样的 json:
let jsonString = """
{
"data": [
{
"name": "Apple",
"price": 44,
"available": true
},
{
"name": "Pear",
"price": 27,
"available": false
}
],
"some_stuff": [],
"some_other_stuff": []
}"""
我的目标是解析data
数组的内容,特别是在一个不关心availibility
属性的结构中。 我不关心返回的some_stuff
和some_other_stuff
是 json。
我创建了一个结构:
struct Fruit: Codable {
let name: String
let price: Int
}
以及上面的一种超级结构:
struct WholeResponse: Codable {
let data: [Fruit]
let someStuff: [Int?]
let someOtherStuff: [Int?]
enum CodingKeys: String, CodingKey {
case data
case someStuff = "some_stuff"
case someOtherStuff = "some_other_stuff"
}
struct Fruit: Codable {
let name: String
let price: Int
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let data = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
name = try data.decode(String.self, forKey: .name)
price = try data.decode(Int.self, forKey: .price)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var data = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
try data.encode(name, forKey: .name)
try data.encode(price, forKey: .price)
}
}
但我发现自己在这样做后非常卡住:
let jsonData = jsonString.data(using: .utf8)!
let jsonDecoder = JSONDecoder()
let fruits = try jsonDecoder.decode(WholeResponse.self, from: jsonData)
我想我遗漏了一些关于我的数据表示的东西,可能会使事情复杂化,但你能帮我解析这个数据数组吗?
首先只需删除您不想要的所有内容:
struct WholeResponse: Codable {
let data: [Fruit]
struct Fruit: Codable {
let name: String
let price: Int
}
}
然后,类似于你以前的,说
let response = try jsonDecoder.decode(WholeResponse.self, from: jsonData)
let fruits = response.data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.