我有这段代码:
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 返回对象数组以将数据正确解码为结构数组时,有什么方法可以使用它吗?
最佳答案
是的,就用这个:
do {
let decoder = JSONDecoder()
let notes = try decoder.decode([NoteRecord].self, from: data)
} catch let err {
print("Error occured:", err)
}
如果你使用 [YourCodableStruct].self
你正在解析数组。如果您使用 YourCodableStruct.self
,您正在解析该结构。
关于ios - 可能从 JSON 数据对象解码的 Codable 结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412875/