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

Xcode项目中JSON解码失败排查:无法解析shifts.json

问题排查与解决

首先,你提供的JSON格式本身是有效的,可以通过以下方式验证:

  • 在Xcode中打开该JSON文件,点击顶部菜单栏的 Editor -> Validate JSON,如果格式错误会直接提示;
  • 把JSON内容复制到任意JSON验证工具中检查。

解析失败的核心原因是数据模型与JSON结构不匹配,加上解码方法吞掉了错误信息导致无法定位问题,具体修正步骤如下:

1. 修正数据模型结构

你的JSON根节点是一个包含shifts数组的对象,而不是直接的[Shift]数组,所以需要新增一个顶层结构体来匹配根结构:

struct ShiftResponse: Codable {
    let shifts: [Shift]
}

struct Shift: Codable {
    let name, role: String
    
    // 修改解码逻辑,先解码顶层对象再取数组
    static let allShifts: [Shift] = {
        do {
            let response = try Bundle.main.decode(file: "shifts.json") as ShiftResponse
            return response.shifts
        } catch {
            print("加载班次数据失败: \(error)")
            return []
        }
    }()
}

2. 优化解码方法,暴露具体错误

原方法中try?会掩盖具体的解码错误,改成do-catch可以打印出详细错误信息,方便后续排查:

extension Bundle {
    func decode<T: Decodable>(file: String) throws -> 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 {
            print("解码错误详情: \(error)")
            throw error
        }
    }
}

完成以上修改后,就能正常解析JSON数据了。如果后续还有解码错误,控制台会打印具体原因(比如键名不匹配、类型不一致等),方便快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:50:25