json - 当我不知道字典的键时,如何从 JSON 解码字典?

标签 json swift xcode swift5

我尝试解码此结构的 JSON:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo

“时间序列(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 ,又可以在最后获取它们以显示具有正确日期的数据。 谢谢

最佳答案

您只需创建您的 StockValue 模型,例如,

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/

相关文章:

ios - 使用核心数据完全不相关的错误

json - 重写 <a> 标签单击事件以在其自己的 <div> 中加载数据

python - 从 JSON 文件中删除项目 - Python

c# - JSON反序列化器继承泛型类型

iOS 构建成功但归档失败

ios - 如何将 RootViewController 更改为另一个 XIB?

ios - 我如何在核心数据中获得 SUM

ios - 以编程方式快速重新加载应用程序

ios - 在 viewDidLoad 中调用时 Firebase 观察者未观察到数据库更改

Swift 包管理器本地化