簡體   English   中英

如何使用可編碼協議在 swift 中為同一結構使用 2 個編碼鍵

[英]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))

Snace 案例示例

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM