You need to enable JavaScript to run this app. JSONDecoder解码[Date:Int]失败 无法将M/d/yy格式日期字符串转为Date
优惠活动
大模型
产品
解决方案
定价
更多

JSONDecoder解码[Date:Int]失败 无法将M/d/yy格式日期字符串转为Date

问题解决:Swift JSONDecoder 解码日期为键的字典失败问题

问题根因

JSON 标准规定所有对象的键只能是字符串类型,JSONDecoder自带的dateDecodingStrategy仅作用于需要解码为Date类型的值,不会自动处理字典键的转换,因此直接声明[Date: Int]类型的属性无法匹配默认解码逻辑,会抛出格式错误。

解决方案

前置准备

首先提取共用的日期格式化器,避免频繁创建影响性能,同时添加固定区域设置避免系统日期格式干扰:

private let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "M/d/yy"
    // 固定区域设置,避免不同地区系统格式导致解析失败
    formatter.locale = Locale(identifier: "en_US_POSIX")
    // 如有需要可自行设置时区,比如UTC时区:formatter.timeZone = TimeZone(secondsFromGMT: 0)
    return formatter
}()

方案1:自定义SubModel解码逻辑(最直接,适配当前场景)

给SubModel实现手动解码方法,先解码为[String: Int]再转换为目标的[Date: Int]类型,不需要再给JSONDecoder设置自定义dateDecodingStrategy:

struct SubModel: Codable {
    let item1, item2: [Date: Int]
    
    enum CodingKeys: String, CodingKey {
        case item1, item2
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 转换item1
        let item1StringMap = try container.decode([String: Int].self, forKey: .item1)
        var item1DateMap = [Date: Int]()
        try item1StringMap.forEach { dateStr, value in
            guard let date = dateFormatter.date(from: dateStr) else {
                throw DecodingError.dataCorruptedError(
                    forKey: .item1,
                    in: container,
                    debugDescription: "无效的日期格式:\(dateStr)"
                )
            }
            item1DateMap[date] = value
        }
        self.item1 = item1DateMap
        
        // 转换item2
        let item2StringMap = try container.decode([String: Int].self, forKey: .item2)
        var item2DateMap = [Date: Int]()
        try item2StringMap.forEach { dateStr, value in
            guard let date = dateFormatter.date(from: dateStr) else {
                throw DecodingError.dataCorruptedError(
                    forKey: .item2,
                    in: container,
                    debugDescription: "无效的日期格式:\(dateStr)"
                )
            }
            item2DateMap[date] = value
        }
        self.item2 = item2DateMap
    }
}

修改后原解码代码可删除自定义dateDecodingStrategy配置,直接解码即可。

方案2:通用扩展适配(适合多处使用日期为键的字典场景)

如果项目中多处需要解码[Date: Int]类型的属性,可以扩展KeyedDecodingContainer添加通用解码方法,避免重复写转换逻辑:

extension KeyedDecodingContainer {
    func decode(_ type: [Date: Int].Type, forKey key: Key, formatter: DateFormatter = dateFormatter) throws -> [Date: Int] {
        let stringMap = try decode([String: Int].self, forKey: key)
        var dateMap = [Date: Int]()
        try stringMap.forEach { dateStr, value in
            guard let date = formatter.date(from: dateStr) else {
                throw DecodingError.dataCorruptedError(
                    forKey: key,
                    in: self,
                    debugDescription: "无效的日期格式:\(dateStr)"
                )
            }
            dateMap[date] = value
        }
        return dateMap
    }
}

使用时SubModel的解码逻辑可简化为:

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    item1 = try container.decode([Date: Int].self, forKey: .item1)
    item2 = try container.decode([Date: Int].self, forKey: .item2)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:00:02