带有动态键的Swift Codable [英] Swift Codable with dynamic keys

查看:118
本文介绍了带有动态键的Swift Codable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JSON结构为:

"periods": {
    "2018-06-07": [
      {
        "firstName": "Test1",
        "lastName": "Test1"
      }
    ],
    "2018-06-06": [
      {
        "firstName": "Test1",
        "lastName": "Test1"
      }
    ]
}

我试图这样解析它:

public struct Schedule: Codable {
    public let periods: Periods
}

public struct Periods: Codable {
    public let unknown: [Inner]

    public struct Inner: Codable {
        public let firstName: String
        public let lastName: String
    }

    private struct CustomCodingKeys: CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }

        var intValue: Int?
        init?(intValue: Int) {
            return nil
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CustomCodingKeys.self)
        self.unknown = try container.decode([Inner].self, forKey: CustomCodingKeys(stringValue: "2018-06-06")
    }
}

但是我只能得到一个值(2018-06-06)的结果.我在这里有多个要解析的日期.这可能吗?

But I can get result for only one value (2018-06-06). I have multiple dates here that I want to parse. Is this possible?

推荐答案

假定您省略了包围该块的{},并且要使此块成为有效JSON,以下是最简单的解决方案要进行解析,您真的不需要处理CodingKey,因为您的名称与JSON中的键匹配,因此合成的CodingKey可以正常工作:

Assuming you left out the { and } that would surround this block and are required for this to be valid JSON, the following is the simplest solution to getting things parsed, you really don't need to deal with CodingKey at all since your names match the keys in the JSON, so the synthesized CodingKey will work just fine:

public struct Schedule: Codable {
    public let periods : [String:[Inner]]
}

public struct Inner: Codable {
    public let firstName: String
    public let lastName: String
}

let schedule = try? JSONDecoder().decode(Schedule.self, from: json)

print(schedule?.periods.keys)

print(schedule?.periods["2018-06-07"]?[0].lastName)

键是外部JSON是具有单个键的JSON对象(字典/映射).periods该键的值是另一个数组映射.像这样分解它,一切都会自动消失.

The key is that the outer JSON is a JSON Object (dictionary/map) with a single key periods The value of that key is another map of arrays. Just break it down like that and everything falls out pretty much automatically.

这篇关于带有动态键的Swift Codable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆