【问题标题】:How should I make the struct to get this JSON data in SwiftUI?我应该如何制作结构以在 SwiftUI 中获取此 JSON 数据?
【发布时间】:2020-03-27 08:51:35
【问题描述】:

我正在发出一个 HTTP GET 请求,我想保存如下所示的 JSON 响应:

{
    "code": 200,
    "status": "success",
    "patients": [
        {
            "_id": "5e77c7bbc7cbd30024f3eadb",
            "name": "Bogdan Patient",
            "username": "bogdanp",
            "phone": "0732958473"
        },
        {
            "_id": "5e77c982a2736a0024e895fa",
            "name": "Robert Patient",
            "username": "robertp",
            "phone": "0739284756"
        }
    ]
}

这是我的结构:

struct Doctor: Codable, Identifiable {
  let id = UUID()
  let patients: [Patients]
}

struct Patients: Codable {
  let id: String
  let name: String
  let phone: String
}

【问题讨论】:

  • 您必须在两个结构中添加 CodingKeys 才能跳过 Doctor 中的 id 并映射 Patients 中的 _id
  • 我该怎么做?您可以将其发布在答案中吗?我不熟悉 CodingKeys。
  • 那你应该做一些研究,也许从苹果那里读到这个article

标签: json swift struct swiftui


【解决方案1】:

根据您的模型,id 应出现在 JSON 中,而 JSON 中的键名是 _id
你可以使用CodingKeys 来解决这个问题:

struct Patients: Codable {
    let id: String
    let name: String
    let phone: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case name
        case phone
    }
}

CodingKeys 在模型中的键名和 JSON 响应中的键名之间创建映射。
使用CodingKeys 还有其他原因,但就您目前的目的而言,这已经足够了。

阅读更多:Codable in Swift

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多