【问题标题】:How to use 2 coding keys for same struct in swift using Codable Protocol如何使用 Codable 协议在 swift 中为同一结构使用 2 个编码键
【发布时间】:2021-07-06 05:14:27
【问题描述】:

所以我在搜索是否有要在其上使用两个不同 API 的 User 结构

struct User {
   var firstName: String
}

第一个 API 的密钥为 firstName,第二个 API 的密钥为 first_Name

【问题讨论】:

  • 后者真的是first_Name?还是first_name?第二种,传统的snake_case,可能性更大。我问是因为如果first_name,那么问题是通过单个struct 定义解决的,只需为JSONDecoder 设置keyDecodingStrategy
  • 如果您自己编写init(from decoder: Decoder),您可以根据需要使用任一键。
  • 但是在你确认你真的必须……之前不要走那条路。
  • @Sulthan 你能解释一下吗
  • @Rob 它是 first_Name 还是 first_name 有区别吗??

标签: json swift protocols decoding codable


【解决方案1】:

重点是使用自定义decoders 而不是自定义键编码!

结构将保持不变:

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 需要哪种解码器(或解码策略)。

【讨论】:

    【解决方案2】:

    一个被忽略的方法是custom 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
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2018-05-23
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多