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

添加id后Swift解析apilist.json报错,求修复方案

解决Swift DecodingError.keyNotFound(缺失"id"键)问题

出现这个错误的核心原因是:新增的id属性在JSON文件中没有对应字段,但默认的Codable解码逻辑会尝试匹配结构体的所有属性,导致找不到键值触发错误。以下是几种实用修复方案:

方案1:给id设置默认生成的UUID(推荐)

直接给id属性赋值默认的UUID,解码时自动生成,无需依赖JSON字段,同时满足Identifiable协议适配List的需求:

struct ApiData: Identifiable, Codable {
    let id: UUID = UUID() // 解码时自动生成唯一ID
    // 保留原有JSON对应的属性,示例:
    let name: String
    let apiUrl: String
}

方案2:用CodingKeys忽略id,自定义解码逻辑

通过自定义CodingKeys指定仅解码JSON中存在的字段,再手动初始化id:

struct ApiData: Identifiable, Codable {
    let id: UUID
    let name: String
    let apiUrl: String
    
    // 只定义JSON中存在的字段作为编码键
    enum CodingKeys: String, CodingKey {
        case name, apiUrl
    }
    
    // 自定义解码初始化方法
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        apiUrl = try container.decode(String.self, forKey: .apiUrl)
        // 手动生成UUID
        id = UUID()
    }
}

方案3:将id设为可选类型(不推荐)

临时解决可以把id设为可选,但List使用时需要处理可选值,不够优雅:

struct ApiData: Identifiable, Codable {
    let id: UUID?
    let name: String
    let apiUrl: String
}

使用List时需要配合compactMap过滤nil值,仅适合临时调试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:27:05