Logo for tanaschita.com

How to use custom names for Swift properties when decoding JSON data

Learn to use Swift's CodingKey protocol.

20 Feb 2023 · 2 min read

Swift's Codable protocol makes it easy to convert JSON data to native Swift types and the other way around. In some cases though, we might need a more customized solution, for example to name Swift properties differently than the JSON keys or to ignore some properties.

Let's look at how to do that.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Codable types allow to declare a nested enumeration named CodingKeys that conforms to the CodingKey protocol. When we do that, the enum cases represent the properties that need to be included. The names of the enumeration cases should match the names we gave to the corresponding properties.

Let's say, we get the following JSON response from the server:

{
"username" : "tanaschita",
"validated": true
}

And we'd like to map it to the following User struct:

struct User: Codable {
let username: String
let isValidated: Bool
}

To map JSON's validated to the isValidated property of the User struct, we can use the mentioned CodingKey protocol as follows:

struct User: Codable {
let username: String
let isValidated: Bool
enum CodingKeys: String, CodingKey {
case username
case isValidated = "validated"
}
}

By specifying raw-values, we control which JSON properties are assigned to which properties of our custom Swift types.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

json

networking

swift

ios

Understanding date decoding strategies when working with JSON in Swift

Learn how to convert JSON dates to Swift's native Date type and vice versa.

14 Nov 2022 · 2 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum