致命错误:无法从应用程序包中解码 .json 数据

问题描述 投票:0回答:1
import Foundation

struct RGBValue: Codable {
    let blue, green: Double
    let timestamp: String
    let red: Double
}

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




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()
        
        guard let loadedData = try? decoder.decode(T.self, from: data) else {
            fatalError("Could not decode \(file) in the project! error : \(Error.self)")

        }
        return loadedData
    }
}

这是整个代码片段,没有显示错误,但在运行时崩溃“线程 1:致命错误:无法解码项目中的 hrv_data.json!错误:错误” 如何解决问题并了解此错误背后的原因?

json 示例:

{
  "fps" : 0.1548667699098587,
  "heartRate" : 81,
  "rgbValues" : [
    {
      "blue" : 0,
      "green" : 0,
      "timestamp" : "22-04-2024 10:33:57",
      "red" : 0
    }]
}
json swift
1个回答
0
投票

我真的很感谢 Paul Hudson 为 Swift 社区做出的巨大努力,但他建议的用于解码 JSON 文件的 Bundle 扩展恐怕是一个糟糕的建议。

强烈建议始终捕获全面的

DecodingError
,它会告诉您到底出了什么问题,甚至错误发生在哪里。

更换

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

do {
    return try decoder.decode(T.self, from: data) 
} catch {
    fatalError("Could not decode \(file) in the project! Error: \(error)")
}
© www.soinside.com 2019 - 2024. All rights reserved.