大家好,如果其中一个字段未知,如何将json结构序列化?
我的json如下:
我的json如下:
{"brands":{"any":false,"19":{"is_all":false,"values":[185,182,178],"include":true},"23":{"is_all":false,"values":[198,199,201],"include":true}},"price":[2000,10000],"year":[1990,2018],"fuel_type":[1,2],"engine_capacity":[\"1.8\",\"4.8\"],"color":[1,2,3],"gearbox_id":[2],"is_georgia":false}
但是:
"19":{"is_all":false,"values":[185,182,178],"include":true}
"23":{"is_all":false,"values":[198,199,201],"include":true}
19和23是未知的值,它们是由API生成的。
因此我的结构如下:
struct auto_order_model: Decodable {
var brands: brand_details <---- this is problem
let price: [Int]
let year: [Int]
let fuel_type: [Int]
let engine_capacity: [String]
let color: [Int]
let gearbox_id: [Int]
let is_georgia: Bool
}
struct brand_details: Decodable {
var any: Bool
var brand_num: [models]?
}
struct models: Decodable {
var is_all: Bool
var values: [Int]
var include: Bool
}
i decode this json like this:
do {
let data = try JSONDecoder().decode(auto_order_model.self, from: json)
print(data)
}catch {
print("JSON Error")
}
因此,在输出上,我得到了品牌编号的nil:
▿ auto_order_model #1
▿ brands : brand_details #1
- any : false
- brand_num : nil
▿ price : 2 elements
- 0 : 2000
- 1 : 10000
▿ year : 2 elements
- 0 : 1990
- 1 : 2018
▿ fuel_type : 2 elements
- 0 : 1
- 1 : 2
▿ engine_capacity : 2 elements
- 0 : "1.8"
- 1 : "4.8"
▿ color : 3 elements
- 0 : 1
- 1 : 2
- 2 : 3
▿ gearbox_id : 1 element
- 0 : 2
- is_georgia : false
any
也是 Models 类型,那么在for key in container.allKeys
中只会有一个属性获得值吗? - sheldorself.any
的赋值将永远不会发生,而是brands
将具有一个键为“any”的条目。 - Gereon