使用未知密钥的Swift 4解码嵌套字典

时间:2019-04-17 07:36:51

标签: swift decodable

我有嵌套字典的json响应,其中每个字典都有动态键/未知键。我想使用Swift Decodable协议对其进行解码,但无法成功对其进行解码。

    {
      "unknownKey1": {
        "data": {
          "user": "Billy"
        },
        "form": "last"
      },
      "2ndUnknownKey": {
        "data": {
          "user": "Gates"
        },
        "form": "third"
      }
      ....(200 more items with unknown key)
    }

我的可编码结构就像:

    struct Response: Codable {
        let keys: [MyData]

        init(from decoder: Decoder) throws {
             let container = try decoder.container(keyedBy: CodingKeys.self)
             let data = try container.decode([String: MyData].self, forKey: .keys)
             keys = Array(data.values)
         }

    }

    struct MyData: Codable {
        let data: [String: User]

    }

    struct User: Codable {
        let user: UserDetail
        let form: String
    }

    struct UserDetail: Codable {
        let user: String
    }

0 个答案:

没有答案