使用KeyedDecodingContainer用随机密钥解码对象

时间:2017-12-20 19:50:12

标签: ios swift codable decodable

我有一个像这样的对象数组,我想解码

let accountPending = """
{
    "blocks": {
        "F143CCC051927EEF59EEA78D16D80F855052BBF159EA6602843904C9445": {
            "amount": "10000000000000000000000000000000",
            "source": "6xswkroybxydyzaxybb1h531sx34omiu7an9t9jy19f9mca7a36s7by5e"
        },
    }
}
""".data(using: .utf8)!

所以我在这些方面尝试了一些事情

struct PendingBlock: Decodable {

let work: [String: PendingBlockData]

enum CodingKeys: String, CodingKey {
    case work = "???"
}

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    self.work = try container.decode(Dictionary.self, forKey: .work)
}

struct PendingBlockData: Decodable {
    let amount: String
    let source: String
}

显然这不起作用,因为work的字符串大小并不是真正的值。一位朋友建议使用KeyedDecodingContainer来获取密钥,但不确定从哪里开始。在这里会有一些帮助。

谢谢!

1 个答案:

答案 0 :(得分:1)

您只需要将字典值struct定义为可解码,并使用String作为字典的键:

let json = """
{
  "blocks": {
    "F143CCC051927EEF59EEA78D16D80F855052BBF159EA6602843904C9445": {
      "amount": "10000000000000000000000000000000",
      "source": "6xswkroybxydyzaxybb1h531sx34omiu7an9t9jy19f9mca7a36s7by5e"
    }
  }
}
"""
let data = Data(json.utf8)
struct Root: Decodable {
    let blocks: [String:Block]
}
struct Block: Decodable {
    let amount: String
    let source: String
}
do {
    let blocks = try JSONDecoder().decode(Root.self, from: data).blocks
    for (key, value) in blocks {
        print(key, value)   // "F143CCC051927EEF59EEA78D16D80F855052BBF159EA6602843904C9445 Block(amount: "10000000000000000000000000000000", source: "6xswkroybxydyzaxybb1h531sx34omiu7an9t9jy19f9mca7a36s7by5e")\n"
    }
} catch {
    print(error)
}