本文介绍了可解码的JSON具有相同标签下的两个结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个json:
{ "stuff": [ { "type":"car", "object":{ "a":66, "b":66, "c":66 }}, { "type":"house", "object":{ "d":66, "e":66, "f":66 }}, { "type":"car", "object":{ "a":66, "b":66, "c":66 }} ]}您可以看到"汽车"和"房屋"中有不同个对象"结构,但它们都在标记对象".
As you can see for "car" and "house" there are different "object" structs, but both under the tag "object".
如果一个人最终得到类似的东西
It would be ideal if one ended up with something like
struct StuffItem: Decodable { let type: TheType let car: Car let house: House }是否有一些可编码的,快速的方式来处理此问题?
Is there some Codable, swifty, way to handle this?
推荐答案我认为最聪明的方式是具有关联类型的枚举
The swiftiest way in my opinion is an enum with associated types
此是有效的JSON
let jsonString = """ { "stuff": [ { "type":"car", "object":{ "a":66, "b":66, "c":66 } },{ "type":"house", "object":{ "d":66, "e":66, "f":66 } },{ "type":"car", "object":{ "a":66, "b":66, "c":66 } } ]} """这些是结构
struct Root : Decodable { let stuff : [Object] } enum Type : String, Decodable { case car, house } struct Car : Decodable { let a, b, c : Int } struct House : Decodable { let d, e, f : Int } enum Object : Decodable { case house(House), car(Car) private enum CodingKeys : String, CodingKey { case type, object } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(Type.self, forKey: .type) switch type { case .car: let carData = try container.decode(Car.self, forKey: .object) self = .car(carData) case .house: let houseData = try container.decode(House.self, forKey: .object) self = .house(houseData) } } }以及用于解码JSON的代码
And the code to decode the JSON
do { let result = try JSONDecoder().decode(Root.self, from: Data(jsonString.utf8)) let objects = result.stuff for object in objects { switch object { case .car(let car): print(car) case .house(let house): print(house) } } } catch { print(error) }更多推荐
可解码的JSON具有相同标签下的两个结构
发布评论