Last active
April 11, 2019 07:32
-
-
Save chiliec/8e431fbf98228b561a98e06ce2f6a439 to your computer and use it in GitHub Desktop.
Example of using custom JSONDecoder().keyDecodingStrategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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