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
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

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
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

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

© 2023 tanaschita.com

Privacy policy

Impressum