You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Codable解析键未知的JSON字典?以Alpha Vantage接口为例

解决AlphaVantage动态时间键的Codable解析问题

我明白你遇到的问题了——AlphaVantage返回的JSON里,Time Series (5min)对应的字典键是动态的时间字符串,而且你之前的模型结构有几个小问题导致解析后拿不到数据,咱们一步步来改:

首先先梳理你原有代码里的问题:

  • 顶层stock结构体里的function属性套了多余的Function结构体,但实际上Time Series (5min)直接就是[String: Value]类型的字典,这会导致解析时找不到values键,直接返回nil;
  • Value结构体里有拼写和键名错误:heigh应该是high,且对应的CodingKey里"2. heigh"多了空格(原JSON键是"2.high"),同理"3. low"也多了空格,应该是"3.low";

接下来是修正后的完整模型代码:

struct StockResponse: Decodable {
    // 直接把Time Series (5min)映射成[String: Value],键就是动态的日期字符串
    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"
    }
}

然后是解析示例,以及如何获取日期键并处理数据:

// 假设你已经拿到网络请求返回的data数据
do {
    let decoder = JSONDecoder()
    let response = try decoder.decode(StockResponse.self, from: data)
    
    // 获取所有日期键,转成数组后可按时间排序(AlphaVantage默认返回降序,可按需调整排序规则)
    let sortedDates = response.timeSeries.keys.sorted { $0 > $1 }
    
    // 遍历处理每个日期对应的行情数据
    for date in sortedDates {
        guard let stockData = response.timeSeries[date] else { continue }
        print("日期:\(date)")
        print("开盘价:\(stockData.open) | 最高价:\(stockData.high) | 收盘价:\(stockData.close)")
        // 其他字段可按需处理
    }
} catch {
    print("解析错误:\(error.localizedDescription)")
}

这样修改后,你就能正常解析到带动态键的字典,并且通过timeSeries.keys获取所有日期字符串,方便后续展示数据。

内容的提问来源于stack exchange,提问作者focafull

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:53:15