gpt4 book ai didi

ios - 单个 JSON 返回的多个可编码对象类型

转载 作者:搜寻专家 更新时间:2023-11-01 07:05:22 24 4
gpt4 key购买 nike

我的困境是我在 JSON 响应中从一个表中接收到两种不同的对象类型。这是返回中两种类型的响应示例。

"supplementaryItems": [
{
"header": "Doodle",
"subHeader": "It's a drawing.",
"slideID": 4,
"imageName": null,
"textItems": null,
"sortOrder": 0
},
{
"header": "Cell Phones",
"subHeader": "No phones please",
"slideID": 8,
"imageName": "welcome_icon_cellphones",
"textItems": ["first","second","third"],
"sortOrder": 1
}
]

我们希望在这里创建两种不同类型的对象。一个 textOnlyItem 和一个 imageWithTextItem

有没有一种方法可以创建一个子类或扩展,可以通过 imageName 是否为 null 定义的 Bool 键控还是不是?

感谢大家的帮助。

最佳答案

您不需要两个不同的对象。只需将 imageNametextItems 声明为可选,这将处理 null 情况。

您可以简单地检查imageName是否为nil

let jsonString = """
{"supplementaryItems": [
{
"header": "Doodle",
"subHeader": "It's a drawing.",
"slideID": 4,
"imageName": null,
"textItems": null,
"sortOrder": 0
},
{
"header": "Cell Phones",
"subHeader": "No phones please",
"slideID": 8,
"imageName": "welcome_icon_cellphones",
"textItems": ["first","second","third"],
"sortOrder": 1
}
]
}
"""

struct Root : Decodable {
let supplementaryItems : [SupplementaryItem]
}

struct SupplementaryItem : Decodable {
let header : String
let subHeader : String
let slideID : Int
let imageName : String?
let textItems : [String]?
let sortOrder : Int
}

do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode(Root.self, from: data)
for item in result.supplementaryItems {
if let imageName = item.imageName {
print(imageName + " has text items")
} else {
print(item.header + " has no text items")
}
}
} catch { print(error) }

关于ios - 单个 JSON 返回的多个可编码对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48388992/

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