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 - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning 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 - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning 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

How to change JSON keys by using Swift's CodingKey protocol

Learn how to map JSON data to a different structure in Swift.

27 Mar 2023 · 3 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum