[英]Decoding JSON with varying key-value pair using Decodable
I am attempting to parse JSON using Decodable that has the following structure and I am being thrown the error: 我正在尝试使用具有以下结构的Decodable解析JSON,但被抛出错误:
does not confirm to protocol "Decodable"
不确认协议“可解码”
The JSON structure looks as such: JSON结构如下所示:
{
base = SGD;
date = "2017-12-29";
rates = {
AUD = "0.95769";
BGN = "1.2205";
THB = "24.414";
TRY = "2.8372";
USD = "0.74844";
ZAR = "9.2393";
};
}
Note that I have shrank the size of the JSON object for readability. 请注意,为了便于阅读,我已经缩小了JSON对象的大小。
The trouble here is that the rates are all different key-value pairs which are unlike the posts here and here . 这里的麻烦在于,费率都是不同的键值对,这与此处和此处的帖子不同。 My code so far as such:
我的代码到目前为止:
struct Fixer: Decodable {
let base: String
let date: String
let rates: [AnyObject]
}
//at dataTasks
do {
let results = try JSONDecoder().decode(Fixer.self, from: data)
print(results.base)
} catch error as NSError {
print(error?.localizedDescription)
}
It would be helpful if anyone could advice under such JSON structure with differing key-value pairs, how should one write the struct? 如果有人可以在这种具有不同键值对的JSON结构下提出建议,那将很有帮助,一个人应该如何编写该结构?
The value for key rates
is a dictionary, not an array. 关键
rates
的值是字典,而不是数组。
The most reasonable way is to decode the object to a dictionary 最合理的方法是将对象解码为字典
let rates: [String:String]
Alternatively create a struct Rate
(for example with members currency
and value
) and write a custom initializer to map the dictionary ( key
-> currency
and value
-> value
) to an array of Rate
或者,创建一个结构化
Rate
(例如,使用员currency
和value
),并编写一个自定义初始化程序,以将字典( key
-> currency
和value
-> value
)映射到Rate
数组
Note: Consider that neither unspecified AnyObject
nor Any
can be used as a destination type. 注意:请考虑未指定的
AnyObject
或Any
不能用作目标类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.