json - 运行时出现多个 JSON CodingKeys 值

标签 json swift

假设我们有一个 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/

相关文章:

ios - 在 Swift 4 中解码 JSON 时遇到问题

swift - 链接请求并使用 RxSwift 返回两个结果

ios - 将 View 的 NSLayoutConstraint 设置为右上角

ios - 将计时器标签格式化为小时 :minutes:seconds in Swift

json - 在 Swift 4 中解析包含字符串和 int 的 JSON 数组

json - 在 Postgres 中获取 JSON 字段键名

ios - 在 UITableView 中显示 Json 结果

ios - 如何将 UITextfield 上的左 View 位置设置为靠近占位符文本

c# - 将 JSON 单个字符串反序列化为数组

ios - 从 'didset' JSON 解码数组数据返回 Nil 值