所以我正在搜索我是否有用户结构,我想在其上使用两个不同的API
struct User {
var firstName: String
}
第一个API有密钥firstName
,第二个API有密钥first_Name
关键是使用自定义decoder
而不是自定义密钥编码!
两者的结构将保持不变:
struct User: Codable {
let firstName: String
}
骆驼案例示例
let firstJSON = #"{ "firstName": "Mojtaba" }"#.data(using: .utf8)!
let firstDecoder = JSONDecoder()
print(try! firstDecoder.decode(User.self, from: firstJSON))
蛇案例示例
let secondJSON = #"{ "first_name": "Mojtaba" }"#.data(using: .utf8)!
let secondDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
print(try! secondDecoder.decode(User.self, from: secondJSON))
此外,您可以实施自己的自定义策略。
因此,请确定每个 API 需要哪种解码器(或解码策略)。
一个被忽视的方法是一个自定义keyDecodingStrategy
,但这需要一个虚拟的CodingKey
结构。
struct AnyKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) { self.stringValue = String(intValue) }
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom({
let currentKey = $0.last!
if currentKey.stringValue == "first_Name" {
return AnyKey(stringValue: "firstName")!
} else {
return currentKey
}
})