Since writing The Ultimate Guide to JSON Parsing in Swift 4, many people have asked me to ask questions about how to properly represent their API with Decodable models.

There’s often a hesitation to add a custom CodingKeys enumeration, which is essentially inevitable because our APIs often use different naming strategies than our Swift apps.

So essentially all of our models would end up defining a CodingKeys enumeration simply to translate between snake_case and camelCase representations of the properties.

In Swift 4.1, however, Apple has addressed this most common point of customization with the new .keyDecodingStrategy on JSONDecoder.

So if you have this JSON response:

{
   "beer": {
       "brewery_name": "Lone Pint",
       "name": "Yellow Rose",
       "beer_style": "IPA"
   }
}

You can now decode this without defining your own CodingKeys

struct Beer : Decodable {
    let breweryName: String
    let name: String
    let beerStyle: String
}

You specify the key strategy before decoding and the decoder will do the work for you.

let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let beer = try jsonDecoder.decode(Beer.self, from: response)

The opposite also works, if you want to take the Beer instance and serialize that to JSON for posting to the server:

let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase
let json = try jsonEncoder.encode(beer)

This new feature is a welcome addition that will be a sensible default for most users. Of course, it won’t work for every API (it’s a wild world out there), but it should be easy enough to drop down to implementing CodingKeys if you need full control. Alternatively, you can create your own key encoding/decoding strategies if you have a different format you need to work with.