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

Swift中Key-Value解码解析失败:含NativeName字段时解码异常的解决方法

解决Swift中Key-Value解码失败的问题

你的问题核心出在nativeName字段的解析逻辑上——注释掉它解码就正常,说明JSON数据和这个字段的模型定义不匹配,或者数据里存在缺失/空值的情况。我给你几个实用的修复方案:

方案1:将nativeName设为可选类型

如果你的JSON中部分城市条目没有nativeName字段,或者该字段的值是null,直接把属性标记为可选就能让解码器跳过错误:

struct Name: Decodable {
    var common, official : String
    var nativeName: [String:NativeName]? // 改为可选类型
    
    enum CodingKeys: String, CodingKey {
        case common, official
        case nativeName = "nativeName"
    }
    
    struct NativeName: Codable {
        let official, common: String
    }
}

这种情况下,解码器遇到缺失或null的nativeName时,会自动将其设为nil,不会抛出解码失败的错误。

方案2:给nativeName设置默认值

如果你希望nativeName永远是一个有效字典(哪怕JSON里没有这个字段),可以通过自定义解码初始化器来提供默认值:

struct Name: Decodable {
    var common, official : String
    var nativeName: [String:NativeName]
    
    enum CodingKeys: String, CodingKey {
        case common, official
        case nativeName = "nativeName"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 必选字段正常解码
        common = try container.decode(String.self, forKey: .common)
        official = try container.decode(String.self, forKey: .official)
        // 尝试解码nativeName,失败则返回空字典
        nativeName = try container.decodeIfPresent([String:NativeName].self, forKey: .nativeName) ?? [:]
    }
    
    struct NativeName: Codable {
        let official, common: String
    }
}

方案3:检查NativeName的结构匹配

如果JSON里的nativeName子字段和你定义的NativeName不匹配(比如部分条目缺少official或common),可以把NativeName里的属性也设为可选,或者给它们添加默认值:

struct NativeName: Codable {
    let official: String?
    let common: String?
    // 或者用默认值:let official: String = ""
}

额外小技巧:定位具体错误

建议你把try?改成do-catch块,打印出具体的解码错误信息,这样能精准定位问题:

do {
    let content = try decoder.decode([City].self, from: data)
    print("解码成功:\(content)")
} catch {
    print("解码错误详情:\(error)")
}

错误信息会明确告诉你是哪个键缺失、类型不匹配,帮你更快解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 00:02:38