Created
March 18, 2020 19:28
-
-
Save axelguilmin/087ab9181c5952e4d95920b302ccab25 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
import Foundation | |
let json = """ | |
{ | |
"Title": "example", | |
"Items": [ | |
"hello", | |
"world" | |
] | |
} | |
""".data(using: .utf8)! | |
struct Model: Codable { | |
let title: String | |
let items: [String] | |
} | |
private extension String { | |
func firstCharLowercased() -> String { | |
prefix(1).lowercased() + dropFirst() | |
} | |
} | |
extension JSONDecoder.KeyDecodingStrategy { | |
static var convertFromPascalCase: JSONDecoder.KeyDecodingStrategy { | |
return .custom { keys -> CodingKey in | |
// keys array is never empty | |
let key = keys.last! | |
// Do not change the key for an array | |
guard key.intValue == nil else { | |
return key | |
} | |
let codingKeyType = type(of: key) | |
let newStringValue = key.stringValue.firstCharLowercased() | |
return codingKeyType.init(stringValue: newStringValue)! | |
} | |
} | |
} | |
let decoder = JSONDecoder() | |
decoder.keyDecodingStrategy = .convertFromPascalCase | |
let model = try! decoder.decode(Model.self, from: json) | |
print(model) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment