You need to enable JavaScript to run this app. Swift入门:Xcode解码JSON出现类型不匹配(mismatch)报错求助
优惠活动
大模型
产品
解决方案
定价
更多

Swift入门:Xcode解码JSON出现类型不匹配(mismatch)报错求助

JSON解码类型不匹配问题根因
  • 触发当前报错的直接原因:JSONDecoder 默认的日期解码策略为 .deferredToDate,该规则下解码器会将Date类型对应的字段当作Double类型的时间戳值解析。当接口返回的Date字段是字符串格式的日期内容时,解码器找不到预期的Double值,就会抛出你看到的“预期解码Double但找到字符串”的类型不匹配错误。
  • 调整完日期解码逻辑后,还会遇到第二处类型不匹配问题:接口返回的Valute结构中,Value、Previous字段是带引号的字符串格式浮点数(例如"91.4331"),但现有模型将这两个字段声明为Double类型,和接口实际返回的数据结构不匹配。
分步骤调整方案

1. 配置兼容接口格式的日期解码规则

接口返回的日期包含两种格式:Date、PreviousDate是纯日期格式(如"2024-05-22"),Timestamp是带时区的ISO8601格式(如"2024-05-22T11:00:00+03:00"),需要替换解码器默认的时间戳解析逻辑,自定义匹配字符串格式的日期解析规则:

// 初始化自定义解码器
let decoder = JSONDecoder()
// 配置两种格式的日期解析器
let isoDateFormatter = DateFormatter()
isoDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let plainDateFormatter = DateFormatter()
plainDateFormatter.dateFormat = "yyyy-MM-dd"
// 配置多格式兼容的日期解码策略
decoder.dateDecodingStrategy = .custom({ decoder in
    let container = try decoder.singleValueContainer()
    let dateString = try container.decode(String.self)
    // 优先解析带时区的时间戳格式
    if let parsedDate = isoDateFormatter.date(from: dateString) {
        return parsedDate
    }
    // 解析失败则尝试纯日期格式
    if let parsedDate = plainDateFormatter.date(from: dateString) {
        return parsedDate
    }
    throw DecodingError.dataCorruptedError(in: container, debugDescription: "无法识别的日期格式:\(dateString)")
})

2. 修正Valute模型的数值字段解码逻辑

接口中Value、Previous字段是字符串格式的数字,新手可以选择最省事的方案:直接把模型里的这两个字段类型从Double改成String,需要做数值计算时再手动转成Double即可;如果想保留Double类型方便直接运算,可以给Valute添加自定义解码方法,自动把字符串转成Double:

struct Valute: Codable {
    var id, numCode, charCode: String
    var nominal: Int
    var name: String
    var value, previous: Double

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case numCode = "NumCode"
        case charCode = "CharCode"
        case nominal = "Nominal"
        case name = "Name"
        case value = "Value"
        case previous = "Previous"
    }

    // 自定义解码逻辑,自动转换字符串格式的数值
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(String.self, forKey: .id)
        numCode = try container.decode(String.self, forKey: .numCode)
        charCode = try container.decode(String.self, forKey: .charCode)
        nominal = try container.decode(Int.self, forKey: .nominal)
        name = try container.decode(String.self, forKey: .name)
        // 替换原本直接解码Double的逻辑,先读取字符串再转换
        let valueString = try container.decode(String.self, forKey: .value)
        value = Double(valueString) ?? 0
        let previousString = try container.decode(String.self, forKey: .previous)
        previous = Double(previousString) ?? 0
    }
}

3. 替换请求方法中的默认解码器

把原有代码中直接使用默认JSONDecoder实例解码的部分,替换成上面已经配置好规则的自定义解码器实例即可:

// 原有错误的解码写法
// let welcome = try JSONDecoder().decode(Welcome.self, from: data)
// 替换为配置完成的解码器
let welcome = try decoder.decode(Welcome.self, from: data)
新手实操提示

用自动工具生成数据模型时,一定要把接口返回的原始JSON内容完整粘贴进工具再生成,不要依赖工具的默认类型推断——很多工具会把带引号的数字默认推断为数值类型,没有和接口实际返回格式对齐,就会反复触发类型不匹配的解码错误。

内容的提问来源于stack exchange,提问作者Кирилл Магеря

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.02 11:06:02