我们可以在 Swift 中使结构体中的 Codable 键不区分大小写吗

Xeb*_*Xeb 3 xcode ios swift codable decodable

我们可以使 Codable 键大小写不敏感吗?不是值,但键本身需要不区分大小写

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"
}
}
Run Code Online (Sandbox Code Playgroud)

这样它就适用于 json:

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

Sample Json 2
{
"a-number" : "12345",
"a-id" : "1",
"addressid" : "3456"
}
Run Code Online (Sandbox Code Playgroud)

小智 6

使用下面的代码将按键设置为小写,以便您可以在您的应用程序中使用。注意:如果您想使用它们,则在此解决方案中,所有键都将变为小写。

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)!
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

要使用这个:

let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .custom(DecodingStrategy.lowercase)
let dataModel = try jsonDecoder.decode(YourDataModel, from: yourdata)
Run Code Online (Sandbox Code Playgroud)