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

Swift中Bundle解析hrv_data.json崩溃问题排查与解决

崩溃原因分析与解决方法

崩溃原因

  • JSON结构与代码类型不匹配:代码中RGB.rgbData被声明为[RGB](数组类型),但提供的JSON是单个RGB对象,并非数组格式。JSONDecoder尝试将单个对象解码为数组,直接导致解码失败。
  • 错误信息无实际价值:decode方法的错误处理中,打印的是Error.self(类型本身)而非实际捕获的错误实例,无法获取真实的解码失败原因,增加排查难度。

解决方法

1. 调整代码适配现有JSON结构

如果业务不需要数组格式,直接修改RGB的静态属性类型,匹配单个JSON对象:

struct RGB: Codable {
    let fps: Double
    let heartRate: Int
    let rgbValues: [RGBValue]
    
    static let sampleData: RGB = Bundle.main.decode(file: "hrv_data.json")
}

2. 修改JSON为数组格式(若业务需要数组)

如果实际场景中需要处理多个RGB对象,将JSON包裹为数组:

[
  {
    "fps": 0.1548667699098587,
    "heartRate": 81,
    "rgbValues": [
      {
        "blue": 0,
        "green": 0,
        "timestamp": "22-04-2024 10:33:57",
        "red": 0
      }
    ]
  }
]

3. 优化错误处理(建议必做)

修改Bundle的decode方法,捕获并打印真实错误,便于后续问题排查:

extension Bundle{
    func decode<T: Decodable>(file: String) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Could not find \(file) in the project!")
        }
        guard let data = try? Data(contentsOf: url) else {
            fatalError("Could not load \(file) in the project!")
        }

        let decoder = JSONDecoder()
        
        do {
            return try decoder.decode(T.self, from: data)
        } catch {
            fatalError("Could not decode \(file) in the project! Error: \(error)")
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:58:18