ios - 获取 api swift 可编码和模型数据中的位置

标签 ios swift codable

我正在从这样的 api 获取数据

[
  {
    "internData": {
      "id": "abc123",
      "name": "Doctor"
    },
    "author": "Will smith",
    "description": "Is an actor",
    "url": "https://www",
  },
  {
    "internData": {
      "id": "qwe900",
      "name": "Constructor"
    },
    "author": "Edd Bett",
    "description": "Is an Constructor",
    "url": "https://www3",
  }
]

我有这样的模型

struct PersonData: Codable {
    let author: String?
    let description: String?
    let url: String?
}

但我不知道如何定义“internData”,我尝试使用另一个模型“InterData”并像 PersonData 一样定义 id 和名称,但我收到错误,我也尝试使用 [String:Any] 但我得到Codable 协议(protocol)错误

我正在使用

let resP = try JSONSerialization.jsonObject(with: data, options: .init()) as? [String: AnyObject]
            print("resP", )

在我的服务/网络脚本中

如果有人知道,谢谢

最佳答案

Codable 的情况下,不能使用 [String:Any] 类型。您需要创建另一个 InternData 模型,供 PersonData 使用。

代码:

JSON 数据:

let jsonData =
"""
[
{
"internData": {
"id": "abc123",
"name": "Doctor"
},
"author": "Will smith",
"description": "Is an actor",
"url": "https://www",
},
{
"internData": {
"id": "qwe900",
"name": "Constructor"
},
"author": "Edd Bett",
"description": "Is an Constructor",
"url": "https://www3",
}
]
"""

//模型

struct PersonData: Codable {
    let author: String?
    let description: String?
    let url: String?
    let internData : InternData?
}

// New model 

struct InternData : Codable {
    let id : String?
    let name : String?
}

//解析

do {
    let parseRes = try JSONDecoder().decode([PersonData].self, from: Data(jsonData.utf8))
    print(parseRes)
}
catch {
     print(error)
}

关于ios - 获取 api swift 可编码和模型数据中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015060/

相关文章:

ios - TraitCollection.horizo​​ntalSizeClass 在 iOS 8.1 上报告紧凑,在 iOS 8.4 和 9.x 上报告常规

swift - NSSecureCoding 与钥匙串(keychain)

ios - SwiftUI Split View大标题不适用于 iPad

ios - 将 Codable/Encodable 快速转换为 JSON 对象

json - 解码异构数组

c# - 使用Unity和ARKit的屏幕截图

objective-c - 核心数据谓词中的异或?

ios - 在 Firebase 身份验证中使用 Google 登录后如何顺利地执行 segue 到 View Controller

json - 如何将 JSON 中的图像解析为 swift4

ios - 将设备唯一 token 发送到推送通知提供商