我发现了很多关于实现解码异构对象数组的示例,但它们并不真正适合我的情况。
这是我的 JSON:
{
"response": [
{
"label": "Shore",
"marineReports": [
{
"id": 1,
"label": "Label"
},
{
"id": 2,
"label": "Label"
}
]
},
{
"label": "Open Sea",
"marineReports": [
{
"id": 0,
"label": "Label"
},
{
"id": 0,
"label": "Label"
}
]
},
{
"label": "Offshore",
"marineReports": [
{
"id": 3,
"label": "Label"
},
{
"id": 3,
"label": "Label"
},
{
"id": 3,
"label": "Label"
}
]
},
{
"label": "Special Reports",
"specialReports": [
{
"label": "Atlantic-Channel",
"reports": [
{
"id": 12,
"label": "Offshore Atlantic"
},
{
"id": 17,
"label": "Channel"
}
]
}
]
}
]
}
这是我最初实现的:
struct ResponseSea: Codable {
let result: [SeaArea]
}
struct SeaArea: Codable {
var label: String
var reports: [MarineReport]
struct MarineReport: Codable {
var id: Int
var label: String
}
}
但后来我发现结果数组中的最后一个对象与其他对象不同。如何为相同对象类型的数组中的特定对象实现自定义解析逻辑?