Home > Software design >  Can we make the Codable key in struct as case insensitive in Swift
Can we make the Codable key in struct as case insensitive in Swift

Time:05-17

Can we make the Codable key case insensitive? NOT VALUE but the KEY ITSELF needs to be case insensitive

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:

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

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

CodePudding user response:

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)
  • Related