【发布时间】:2019-09-27 05:07:54
【问题描述】:
我的客户有一个返回 Article 对象的服务。有一个 id 属性,它是 UInt64 类型。在同一个 api 中,当您询问类别文章时,您会收到文章的响应,但 id 是一个字符串。目前没有办法有人会改变这个愚蠢的事情,所以我必须找到一种解决方法来解析这两个答案。我的模型是这样的:
struct Article {
let id: UInt64
let categoryName: String?
}
extension Article: Decodable {
private enum Keys: String, CodingKey {
case id
case categoryName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
id = try container.decode(UInt64.self, forKey: Keys.id)
categoryName = try container.decodeIfPresent(String.self, forKey: Keys.categoryName)
}
如何查看Keys.id的类型并使用正确的方法进行解码? 我必须同时使用两个
id = try container.decode(UInt64.self, forKey: Keys.id)
id = try container.decode(String.self, forKey: Keys.id)
在这两种情况下都正确解析我的对象。提前致谢
【问题讨论】: