swift - 带有 Codable 的可失败初始化器
问题描述
我正在尝试解析项目数组的以下 json 模式,itemID 可能不为空。如何使itemID
JSON 中不存在项目 nil id?
[{
"itemID": "123",
"itemTitle": "Hello"
},
{},
...
]
我的可解码类如下:
public struct Item: : NSObject, Codable {
let itemID: String
let itemTitle: String?
}
private enum CodingKeys: String, CodingKey {
case itemID
case itemTitle
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
itemID = try container.decode(String.self, forKey: .itemID)
itemTitle = try container.decodeIfPresent(String.self, forKey: .itemTitle)
super.init()
}
}
解决方案
首先,itemID
is an Int
and not String
in your JSON
response。所以struct Item
看起来,
public struct Item: Codable {
let itemID: Int?
let itemTitle: String?
}
解析之JSON
类的,
if let data = data {
do {
let items = try JSONDecoder().decode([Item].self, from: data).filter({$0.itemID == nil})
print(items)
} catch {
print(error)
}
}
在上面的代码中,您可以简单地filter
使用itemID == nil
.
推荐阅读
- python - 我需要做什么才能检测到我的麦克风?
- c# - C# GetRange 包装
- microsoft-graph-api - 通过 Microsoft Graph API 创建的 OnlineMeeting 的会议 ID,电话拨号到期
- c++ - 为每个非数字字符打印 C++ 数据验证
- c# - 同一用户控件的不同WPF网格行大小规格取决于情况
- python - Pandas:如何通过大于考虑索引来过滤列
- docker - 如何使用 Kubernetes statefulset 调整 Redis 配置?
- google-cloud-platform - 大查询 STRING_AGG() 多个字段产生错误
- azure-ad-b2c - Azure B2C:使用“CompareClaims”TransformationMethod 将密码重置过程中的用户密码与电子邮件前缀进行比较
- image - 我无法在 NextJS 中加载图像