Skip to content

Instantly share code, notes, and snippets.

@axelguilmin
Created March 18, 2020 19:28
Show Gist options
  • Save axelguilmin/087ab9181c5952e4d95920b302ccab25 to your computer and use it in GitHub Desktop.
Save axelguilmin/087ab9181c5952e4d95920b302ccab25 to your computer and use it in GitHub Desktop.
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