我正在尝试解析以下项目数组的 json 模式,itemID 可能不为空。如何使项目的 ID 为零itemID
JSON 中不存在?
[{
"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
并不是String
在你的JSON
回复。所以struct Item
好像,
public struct Item: Codable {
let itemID: Int?
let itemTitle: String?
}
解析JSON
like,
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)