Last active
December 21, 2019 05:37
-
-
Save hlung/5845ebb5d22c6a57fd09f12e2fe14238 to your computer and use it in GitHub Desktop.
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
struct UserSettings: Codable { | |
let someBool: Bool | |
let someDate: Date | |
enum CodingKeys: String, CodingKey { | |
case someBool = "someDifferentKeyBool" | |
case someDate = "someDifferentKeyDate" | |
} | |
} | |
extension JSONDecoder { | |
static var snakeCaseISO8601Date: JSONDecoder = { | |
let decoder = JSONDecoder() | |
decoder.keyDecodingStrategy = .convertFromSnakeCase | |
decoder.dateDecodingStrategy = .iso8601 | |
return decoder | |
}() | |
} | |
let data = """ | |
{ | |
"some_different_key_bool": true, | |
"some_different_key_date": "2019-02-06T00:35:01Z" | |
} | |
""".data(using: .utf8)! | |
let obj = try JSONDecoder.snakeCaseISO8601Date.decode(UserSettings.self, from: data) | |
print(obj) // UserSettings(someBool: true, someDate: 2019-02-06 00:35:01 +0000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment