ios - 可能从 JSON 数据对象解码的 Codable 结构数组

标签 ios json swift

我有这段代码:

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/

相关文章:

swift - 选择自定义单元格会激活另一个单元格

ios - 如何在 UITableView 滚动时缩小 UIImageView 内容(图像)?

ios - @availability 关键字在 Xcode "alt+click"文档助手中不起作用

ios - 如何通过以编程方式创建 UIImage 来更改 UITabBar 顶部边框的颜色?

json - OSX 上的家长控制导致问题

ios - Swift 选项卡栏已隐藏但自定义按钮仍处于事件状态

ios - 当我在 VC B 中时,如何使用本应在 VC A 中使用的通知中的数据

python - Django queryset - 从 json 对象转换

c# - JSON 对象帮助

Swift 3 Coredata 出错