json - 我应该如何制作结构以在 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
}
解决方案
根据您的模型,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
但对于您当前的目的,这已经足够了。
阅读更多:在 Swift 中可编码
推荐阅读
- spring - 身份验证弹簧安全
- r - 绘图 shapefile 变量:错误无效灰度级,必须在 [0,1] 中。R
- elasticsearch - 启动 elasticsearch 时出错,错误提示无法将传输端口绑定到 9093
- python - 在数组数组中总结不同形状的数组列-Python 3.x
- react-native - 如何在 react-native 中更改父级的变量
- r - R问题存储为因子R的日期列无法转换
- rust - 我可以从自定义类型中借用切片吗?
- r - 生成一个变量来计算连续条目
- python-xarray - Xarray:具有不同粒度/级别相同层次结构/多索引的多维数据集的操作
- vue.js - 如何在vue中隐藏元素?