gpt4 book ai didi

ios - 具有同一标签下的两个结构的 JSON 可解码

转载 作者:行者123 更新时间:2023-11-28 18:14:50 25 4
gpt4 key购买 nike

我有这个 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 }}
]}

如您所见,“car”和“house”有不同“object”结构,但都在标签“对象”。

如果最后能得到这样的东西就太理想了

struct StuffItem: Decodable {       
let type: TheType
let car: Car
let house: House
}

是否有一些可编码的、快速的方法来处理这个问题?

最佳答案

在我看来,最快捷的方法是使用关联类型的枚举

这是有效的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的代码

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

关于ios - 具有同一标签下的两个结构的 JSON 可解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com