简体   繁体   English

我们可以在 Swift 中将结构中的 Codable 键设置为不区分大小写吗

[英]Can we make the Codable key in struct as case insensitive in Swift

Can we make the Codable key case insensitive?我们可以使 Codable 键不区分大小写吗? NOT VALUE but the KEY ITSELF needs to be case insensitive NOT VALUE 但 KEY ITSELF 需要不区分大小写

struct Model: Codable, Equatable {
let number: String?
let id: String?
let address: String?

enum CodingKeys: String, CodingKey {
case number = "A-Number"
case id = "A-Id"
case address = "AddressId"
}
}

So that it works for both json:所以它适用于两个json:

Sample Json 1
{
"A-Number" : "12345",
"A-Id" : "1",
"AddressId" : "3456"
}

Sample Json 2
{
"a-number" : "12345",
"a-id" : "1",
"addressid" : "3456"
}

use the below code for making the keys lowercase, so that you can use throught your application.使用以下代码将键设为小写,以便您可以在应用程序中使用。 NOTE: All your keys will be lowercased with this solution, if you want to use them.注意:如果您想使用此解决方案,您的所有密钥都将小写。

struct AnyKey: CodingKey {
      var stringValue: String

      init?(stringValue: String) {
        self.stringValue = stringValue
      }

      var intValue: Int? {
        return nil
      }

      init?(intValue: Int) {
        return nil
      }
    }
    
    struct DecodingStrategy {
        static var lowercase: ([CodingKey]) -> CodingKey {
            return { keys -> CodingKey in
                let key = keys.first!
                let modifiedKey = key.stringValue.prefix(1).lowercased() + key.stringValue.dropFirst()
                return AnyKey(stringValue: modifiedKey)!
            }
        }
    }

To use this:要使用这个:

let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .custom(DecodingStrategy.lowercase)
let dataModel = try jsonDecoder.decode(YourDataModel, from: yourdata)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM