用动态键解析json

问题描述

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

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

我的结构

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值的 array -只是单个Coin值。

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

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

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

然后,您会因为typeMismatch键:btc而遇到"Expected to decode Array<Any> but found a dictionary instead."错误,这至少会给您提示去哪里看。