首页 > 解决方案 > 我应该如何制作结构以在 SwiftUI 中获取此 JSON 数据?

问题描述

我正在发出 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
}

标签: jsonswiftstructswiftui

解决方案


根据您的模型,idJSON 中是预期的,而 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但对于您当前的目的,这已经足够了。

阅读更多:在 Swift 中可编码


推荐阅读