例如,您必须编写一个自定义初始化程序来处理这些情况
struct Thing : Decodable {
let scanCode, name, scanId : String
private enum CodingKeys: String, CodingKey { case scanCode = "ScanCode", name = "Name", ScanID, Id }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scanCode = try container.decode(String.self, forKey: .scanCode)
name = try container.decode(String.self, forKey: .name)
if let id = try container.decodeIfPresent(String.self, forKey: .Id) {
scanId = id
} else {
scanId = try container.decode(String.self, forKey: .ScanID)
}
}
}
首先尝试解码一个密钥,如果它无法解码另一个。
为方便起见,我跳过了attributes
关键