使用KeyedDecodingContainer用随机密钥解码对象 [英] Using KeyedDecodingContainer to decode an object with a random key

查看:229
本文介绍了使用KeyedDecodingContainer用随机密钥解码对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要解码的对象数组

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
}

显然,这是行不通的,因为 work 不是真正的价值。一位朋友建议使用 KeyedDecodingContainer 来获取密钥,但不确定从何处开始。希望在这里有所帮助。

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.

谢谢!

推荐答案

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

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

这篇关于使用KeyedDecodingContainer用随机密钥解码对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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