可解码的JSON具有相同标签下的两个结构

编程入门 行业动态 更新时间:2024-10-10 15:18:29
本文介绍了可解码的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具有相同标签下的两个结构

本文发布于:2023-11-29 04:26:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   结构   标签   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!