问题
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