当我不知道字典的键时,如何从JSON解码字典? [英] How can I decode a dictionary from a JSON when I don't know the keys of the dictionary?
问题描述
我尝试对这种结构的JSON进行解码:
I try to decode a JSON of this structure:
时间序列(5分钟)"对象是对象的字典,但是当每次加载JSON时字典的键都发生变化时,我不知道如何使用可编码协议解码此JSON.
The "Time Series (5min)" Object is a dictionary of Objects, but I don't know how to decode this JSON using the Codable Protocol when the keys of the dictionary are changing whenever I load the JSON.
我试图编写一些模型,但是每当我尝试访问字典时,我都会得到零.
I tried to write some models, but whenever I try to access the dictionary I get nil.
struct stock: Decodable{
let function: Function?
enum CodingKeys: String, CodingKey {
case function = "Time Series (5min)"
}
}
struct Function: Decodable{
let values: [String:Value]
}
struct Value: Decodable{
let open: String
let heigh: String
let low: String
let close: String
let volume: String
enum CodingKeys: String, CodingKey{
case open = "1.open"
case heigh = "2. heigh"
case low = "3. low"
case close = "4.close"
case volume = "5.volume"
}
}
我该如何以不需要预先知道键的方式编写代码,但也可以在最后获得它们以显示具有正确日期的数据. 谢谢
How can I write my code in a way that I don't need to know the keys in advance, but also get them at the end to display the data with the correct date. Thank you
推荐答案
您只需创建自己的Stock
和Value
模型,例如
You an simply create your Stock
and Value
models like,
struct Stock: Decodable {
let timeSeries: [String:Value]
enum CodingKeys: String, CodingKey {
case timeSeries = "Time Series (5min)"
}
}
struct Value: Decodable {
let open: String
let high: String
let low: String
let close: String
let volume: String
enum CodingKeys: String, CodingKey{
case open = "1. open"
case high = "2. high"
case low = "3. low"
case close = "4. close"
case volume = "5. volume"
}
}
不需要单独的struct Function
.
使用JSONDecoder
之类的解析您的回复,
Parse your response using JSONDecoder
like,
do{
let response = try JSONDecoder().decode(Stock.self, from: data)
print(response)
} catch {
print(error)
}
这篇关于当我不知道字典的键时,如何从JSON解码字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!