使用动态键解析 json

parsing json with dynamic keys

我已经为此工作了几个小时,但一直未能找到答案。我有一个带有动态键的 JSON,我正试图将其解析为一个结构。我以为我可以保持简单,但我遇到了序列化错误。请帮忙 - 谢谢

{"rates":{
   "btc":{"name":"Bitcoin","unit":"BTC","value":1.0,"type":"crypto"},
   "eth":{"name":"Ether","unit":"ETH","value":35.69,"type":"crypto"},
}}

我的结构

struct CryptoCoins: Decodable {
   let rates: [String: [Coin]]
}

struct Coin: Decodable {
   let name: String
   let unit: String
   let value: Double
   let type: String
}

我的解码器:

guard let container = try? JSONDecoder().decode(CryptoCoins.self, from: json) else {
   completion(.failure(.serializationError))  // <- failing here
   return
}

您正在将 属性 rates 解码为错误的类型 - 它不是 String 键的字典和 数组 Coin 值 - 这只是一个 Coin 值。

struct CryptoCoins: Decodable {
   let rates: [String: Coin] // <- here
}

在相关说明中,不要使用 try? 隐藏错误。如有必要,捕获并记录它:

do {
   let cryptoCoins = try JSONDecoder().decode(CryptoCoins.self, from: json)
   // ..
} catch {
   print(error)
}

那么你会得到 btc 键的 typeMismatch 错误:"Expected to decode Array<Any> but found a dictionary instead.",这至少会提示你去哪里找。