[英]How to use 2 coding keys for same struct in swift using Codable Protocol
因此,我正在搜索是否有要在其上使用兩個不同 API 的用戶結構
struct User {
var firstName: String
}
第一個 API 有 key firstName
,第二個有 key 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
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.