Using KeyedDecodingContainer to decode an object with a random key

我是研究僧i 提交于 2020-01-06 06:45:48

问题


I have an array of objects that looks like this that I want to decode

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

So I'm trying something along these lines

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
}

Obviously this isn't going to work, since the string case for work isn't a real value. A friend recommended using KeyedDecodingContainer to get the keys but wasn't sure where to start with that. Would love some help here.

Thanks!


回答1:


You just need to pass the define the dictionary value struct as decodable and use a String as the key for your dictionaries:


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)
}


来源:https://stackoverflow.com/questions/47913410/using-keyeddecodingcontainer-to-decode-an-object-with-a-random-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!