简体   繁体   English

如何使用可编码协议在 swift 中为同一结构使用 2 个编码键

[英]How to use 2 coding keys for same struct in swift using Codable Protocol

So I was searching if I have User struct that I want to use two different APIs on it因此,我正在搜索是否有要在其上使用两个不同 API 的用户结构

struct User {
   var firstName: String
}

first API has the key firstName , second one has the key first_Name第一个 API 有 key firstName ,第二个有 key first_Name

The point is to use custom decoder s not custom key codings!关键是使用自定义decoder而不是自定义键编码!

The struct will stay the same for both:两者的结构将保持不变:

struct User: Codable {
    let firstName: String
}

Camel Case Example骆驼案例示例

let firstJSON = #"{ "firstName": "Mojtaba" }"#.data(using: .utf8)!

let firstDecoder = JSONDecoder()

print(try! firstDecoder.decode(User.self, from: firstJSON))

Snace Case Example 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))

Also, You can implement your own custom strategy.此外,您可以实施自己的自定义策略。

So decide which decoder (or decoding strategy) you need for each API.所以决定每个 API 需要哪种解码器(或解码策略)。

A neglected approach is a custom keyDecodingStrategy , however this requires a dummy CodingKey struct.一种被忽略的方法是自定义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