假设我们有一个 JSON 结构如下:
{
"July": [
{
...
"startDate": "July 10",
"endDate": "July 11",
...
},
{
...
},
{
...
},
{
...
}
]
}
我正在尝试使用以下结构解析此 API,仅使用 native swift。
struct Listing: Codable {
let months: [Month]
enum CodingKeys: String, CodingKey {
case months = "June" //here we need all months for the whole year.
}
}
struct Month: Codable {
...
let startDate: String
let endDate: String
...
enum CodingKeys: String, CodingKey {
...
}
}
问题是每次新的 JSON 响应和新的月份时,API 都会按请求返回,因此我需要几个“CodingKeys”案例:“七月”、“八月”等,同时 Month 结构可重复使用。 有一个想法可以解决映射实体的问题,但我想可以有一个更优雅的解决方案。如果您对如何简化解决方案有任何想法,请告诉我。
最佳答案
首先,如果您只想解码 JSON,则只采用 Decodable
。
我建议将 months
解码为字典 [String:[Month]]
struct Listing: Decodable {
let months: [String:[Month]]
}
然后通过已知的月份键获取 Month
数组。
或者使用枚举
enum MonthName : String, Decodable {
private enum CodingKeys : String, CodingKey { case january = "January", february = "February", ... december = "December" }
case January, February, ... December
}
struct Listing: Decodable {
let months: [MonthName:[Month]]
}
编辑:
您还可以编写自定义初始化程序来提取 Month
数组,它假定根对象中只有一个字典和一个键值对。
struct Listing: Decodable {
let months: [Month]
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let monthData = try container.decode([String:[Month]].self)
months = monthData[monthData.keys.first!]!
}
}
关于json - 运行时出现多个 JSON CodingKeys 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011453/