我尝试解码此结构的 JSON:
“时间序列(5分钟)”对象是一个对象字典,但当我加载 JSON 时字典的键发生变化时,我不知道如何使用可编码协议(protocol)解码此 JSON。
我尝试编写一些模型,但每当我尝试访问字典时,我都会得到 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"
}
}
如何编写代码,既不需要提前知道 key ,又可以在最后获取它们以显示具有正确日期的数据。 谢谢
最佳答案
您只需创建您的 Stock
和 Value
模型,例如,
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
解析您的响应,例如,
do{
let response = try JSONDecoder().decode(Stock.self, from: data)
print(response)
} catch {
print(error)
}
关于json - 当我不知道字典的键时,如何从 JSON 解码字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555878/