Skip to content

Instantly share code, notes, and snippets.

@chiliec
Last active April 11, 2019 07:32
Show Gist options
  • Save chiliec/8e431fbf98228b561a98e06ce2f6a439 to your computer and use it in GitHub Desktop.
Save chiliec/8e431fbf98228b561a98e06ce2f6a439 to your computer and use it in GitHub Desktop.
Example of using custom JSONDecoder().keyDecodingStrategy
import Foundation
// What if we wait lowercased key, but suddenly has come uppercased? JSONDecoder().keyDecodingStrategy!
let json = """
{"NAME": "Vova"}
"""
struct Model: Decodable {
let name: String
enum CodingKeys: String, CodingKey {
case name // wait lowercased key
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: CodingKeys.name)
}
}
struct UppercasedKey: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) {
fatalError("init?(intValue:) has not been implemented")
}
init(stringValue: String) {
self.stringValue = stringValue.lowercased()
}
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom({ (keys) -> CodingKey in
let key = keys.last!.stringValue
return UppercasedKey(stringValue: key)
})
do {
let result = try decoder.decode(Model.self, from: Data(json.utf8))
print(result.name)
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment