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

SwiftData中JSON日期字符串解码失败问题求助

解决Google Books API日期解码失败问题

核心原因排查

从报错信息看,第8条items数据的publishedDate不符合你设置的yyyy-MM-dd格式——Google Books API返回的日期并非统一格式,部分书籍可能仅返回年份(如"2016")或年月(如"2016-02"),导致单一格式的解析器失效。另外,未指定DateFormatter的locale和时区也可能引发解析异常。

具体解决方案

  1. 配置兼容多格式的日期解析策略
    替换单一格式的dateDecodingStrategy,添加对多种日期格式的支持:

    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .custom { decoder in
        let container = try decoder.singleValueContainer()
        let dateString = try container.decode(String.self)
        
        // 覆盖API可能返回的所有日期格式
        let validFormats = ["yyyy-MM-dd", "yyyy-MM", "yyyy"]
        for format in validFormats {
            let formatter = DateFormatter()
            formatter.dateFormat = format
            formatter.locale = Locale(identifier: "en_US_POSIX") // 强制使用美式区域设置,避免解析偏差
            formatter.timeZone = TimeZone(secondsFromGMT: 0) // 统一时区为UTC
            
            if let date = formatter.date(from: dateString) {
                return date
            }
        }
        // 若所有格式都不匹配,抛出自定义错误(可选)
        throw DecodingError.dataCorruptedError(in: container, debugDescription: "无法解析日期格式:\(dateString)")
    }
    
  2. 确保SwiftData模型解码逻辑正确
    若你的VolumeInfo是SwiftData的@Model类,需确保自定义的init(from decoder: Decoder)方法正确使用了解码器的策略,且publishedDate的CodingKey与API返回的键名完全一致(注意大小写:"publishedDate")。

  3. 验证出错数据的实际格式
    打印第8条items的publishedDate值,确认其具体格式,可针对性补充到validFormats数组中。

额外提示

  • 避免直接修改SwiftData模型的encode/decode方法时遗漏逻辑,若无需自定义编码,可依赖SwiftData的自动合成实现。
  • 计算属性formattedPublishedDate可使用Date.FormatStyle简化实现,无需额外维护DateFormatter:
    var formattedPublishedDate: String {
        guard let date = publishedDate else { return "未知日期" }
        return date.formatted(.dateTime.year().month().day())
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:08:26