WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>

Auto-convert JSON snake case to Swift camel case properties

Snake case is a naming convention where words are separated by underscores and presented in lowercase, such as user_name or account_id. This format is commonly found in JSON responses from APIs. In contrast, Swift typically uses camel case for naming properties, where the first word is lowercase and each subsequent word starts with an uppercase letter, like userName or accountId. When working with JSON data, we often encounter a mismatch between the JSON's snake case keys and Swift's camel case property names.

Fortunately, we can address this challenge with the convertFromSnakeCase decoding strategy, a feature of the JSONDecoder class from the Foundation framework. This strategy automatically converts snake case names from JSON into camel case properties in our Swift models, eliminating the need for manual mapping of JSON keys to model properties.

Consider the following JSON object and corresponding Swift model:

  "user_id": 123,
  "user_name": "JohnDoe"
struct User: Codable {
    var userId: Int
    var userName: String

Here is how we can use the convertFromSnakeCase strategy to decode the data:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

// User(userId: 123, userName: "JohnDoe")
let user = try? decoder.decode(User.self, from: data)

By setting the keyDecodingStrategy of JSONDecoder to .convertFromSnakeCase, we instruct the decoder to automatically map user_id to userId and user_name to userName during decoding. We don’t need to write custom decoding logic or use coding keys for each property. This keeps our model definitions cleaner and more consistent with Swift's naming conventions.

Using this strategy simplifies the process of working with JSON data in Swift and ensures our code remains clean and maintainable.

If you're an experienced Swift developer looking to learn advanced techniques, check out my new book Swift Gems. It’s packed with tips and tricks focused solely on the Swift language and Swift Standard Library. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice that will elevate your Swift development skills to the next level. Grab your copy of Swift Gems and let's explore these advanced techniques together.

Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

    100+ tips to take your Swift code to the next level

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.