Last active
March 28, 2020 14:02
-
-
Save amittkashyap/c45ef80bfefab8a901e640f5e5bfedcf to your computer and use it in GitHub Desktop.
In this gist I will show you how to use custom keyDecodingStrategy/keyEncodingStrategy in new Codable/Decodable protocols in swift 4.1 with a simple example.
This file contains hidden or 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
let json = """ | |
[ | |
{ | |
"first-Name": "Taylor", | |
"last-Name": "swift", | |
"age": 28 | |
}, | |
{ | |
"first-Name": "Tom", | |
"last-Name": "hanks", | |
"age": 61 | |
} | |
] | |
""" | |
struct Person: Codable { | |
var firstName: String | |
var lastName: String | |
var age: Int | |
} | |
struct PersonKey: CodingKey { | |
var stringValue: String | |
var intValue: Int? | |
init?(stringValue: String) { | |
self.stringValue = stringValue | |
self.intValue = nil | |
} | |
init?(intValue: Int) { | |
self.stringValue = String(intValue) | |
self.intValue = intValue | |
} | |
} | |
let jsonDecoder = JSONDecoder() | |
//here you set the strategy, could be .convertFromSnakeCase apart from .useDefaultKeys. So basically we dont need the `CodingKeys enumerations` anymore | |
jsonDecoder.keyDecodingStrategy = .custom { keys -> CodingKey in | |
let key = keys.last!.stringValue.split(separator: "-").joined() | |
return PersonKey(stringValue: String(key))! | |
} | |
do { | |
let persons = try jsonDecoder.decode([Person].self, from: Data(json.utf8)) | |
print(persons) | |
} catch { | |
print(error.localizedDescription) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment