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

如何用现有Codable结构体代码解码REST API返回的对象数组?

如何用现有Codable结构体解码REST API返回的对象数组?

我编写了如下的Codable结构体:

struct NoteRecord: Codable {
    let id: String
    let title: String
    let detail: String?
    let dueDate: String?

    private enum CodingKeys: String, CodingKey {
        case id, title, detail, dueDate
    }
}

以及对应的解析代码:

do {
    let decoder = JSONDecoder()
    let note = try decoder.decode(NoteRecord.self, from: data)
} catch let err {
    print("Error occured:", err)
}

请问当REST API返回对象数组时,能否利用这些代码将数据正确解码为结构体数组?


回答

不行哦,你当前的代码只能解码单个NoteRecord对象,没办法直接处理数组类型的返回结果。不过修改起来超简单,只需要调整decode方法的目标类型,把它改成[NoteRecord].self(也就是NoteRecord的数组类型)就可以了。

修改后的解析代码如下:

do {
    let decoder = JSONDecoder()
    // 将解码目标从单个对象替换为数组类型
    let notes = try decoder.decode([NoteRecord].self, from: data)
    // 现在notes就是NoteRecord的数组,你可以正常遍历、操作它
    for note in notes {
        print("获取到笔记:\(note.title)")
    }
} catch let err {
    print("解码出错:", err)
}

这里的核心逻辑是:JSONDecoder的decode方法支持任意遵循Decodable协议的类型,而数组类型(比如[T],只要T实现了Decodable)天然就符合这个协议。你的NoteRecord已经实现了Codable(它同时包含Decodable和Encodable能力),所以直接用数组类型作为解码目标,就能完美适配API返回的数组数据啦。

额外提一句:如果API返回的是嵌套结构(比如外层有个data字段包裹着数组),那你可能需要额外定义一个包含数组的结构体来适配,但如果是直接返回数组的话,上面的修改就完全足够了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:28:04