解码异构数组
Decoding Heterogeneous Array
我找到了很多关于解码异构对象数组的实现的例子,但它们并不适合我的情况。
这是我的 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
}
}
但后来我发现结果数组中的最后一个对象与其他对象不同。
如何为相同对象类型的数组中的特定对象实现自定义解析逻辑?
根据你的JSON应该是这样的:
struct RootObject: Codable {
let response: [Response]
}
struct Response: Codable {
let label: String
let marineReports: [Report]?
let specialReports: [SpecialReport]?
}
struct Report: Codable {
let id: Int
let label: String
}
struct SpecialReport: Codable {
let label: String
let reports: [Report]
}
marineReports
和 specialReports
是可选的,因为它们可能不存在。
我找到了很多关于解码异构对象数组的实现的例子,但它们并不适合我的情况。
这是我的 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
}
}
但后来我发现结果数组中的最后一个对象与其他对象不同。 如何为相同对象类型的数组中的特定对象实现自定义解析逻辑?
根据你的JSON应该是这样的:
struct RootObject: Codable {
let response: [Response]
}
struct Response: Codable {
let label: String
let marineReports: [Report]?
let specialReports: [SpecialReport]?
}
struct Report: Codable {
let id: Int
let label: String
}
struct SpecialReport: Codable {
let label: String
let reports: [Report]
}
marineReports
和 specialReports
是可选的,因为它们可能不存在。