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

如何将API返回的JSON转换为User数组并解决解码错误?

解决API JSON解码为User数组的keyNotFound错误

问题背景

API返回的JSON结构外层包含object和data字段,其中data是存储多个账户对象的数组:

{"object": "list","data": [{"id": "acct_1MksGkPS84v9RDr2","object": "account",...}]}

已定义遵循Codable协议的User结构体:

struct User: Codable {
    var id: String; var email: String; //... 其他属性
}

现有解码代码尝试直接将JSON解码为User实例,触发以下错误:

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(User.self, from: data); 
    accounts = [result]
} catch {
    print("Failed to decode JSON: \(error)")
}

错误信息:

Failed to decode JSON: keyNotFound(CodingKeys(stringValue: "id", intValue: nil), ...)

错误原因

直接解码User.self不符合JSON的实际结构:JSON根节点是一个包含data数组的外层对象,而非单个User对象。解码器在根节点找不到User所需的id键,因此抛出keyNotFound错误。

解决方案

1. 定义匹配外层结构的响应结构体

创建一个遵循Codable的结构体,完全匹配API返回的JSON外层结构:

struct UserListResponse: Codable {
    let object: String
    let data: [User]
}

2. 修改解码逻辑,提取User数组

调整解码代码,先解析外层响应对象,再从中取出data数组:

let decoder = JSONDecoder()
do {
    let response = try decoder.decode(UserListResponse.self, from: data)
    accounts = response.data // 直接获取User数组
} catch {
    print("JSON解码失败: \(error)")
}

3. 处理可选属性(可选)

如果API返回的User对象中存在可能缺失的字段(比如email),需要将User的对应属性声明为可选类型,避免因字段缺失导致解码失败:

struct User: Codable {
    var id: String
    var email: String? // 改为可选类型
    //... 其他属性按需设置为可选
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:10:06