JSON Coding Key in Swift

JSON Coding Key in Swift

A tutorial on parsing JSON data with mismatching parameter name using a CodingKeys enum

·

3 min read

In SwiftUI, we often work with data that comes from an external source, such as JSON data from an API or data from a database. When working with this type of data, we may need to convert between the external representation and our internal representation. Coding keys provide a way to specify the mapping between the keys in the external representation and the properties in our Swift structs. In this blog post, we'll explore how to use coding keys in SwiftUI.

The code in this post is available here.

Let's start with an example. Suppose we have the following JSON data:

{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com"
}

We can create a Swift struct to represent the model of this data:

struct Person: Codable {
    var name: String
    var age: Int
    var email: String
}

We can use the JSON decoder to convert between the JSON data and our Person struct since the struct is conforming to the Codable protocol.

let json = """
{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: json)

In this example, the keys in the JSON data match the property names in our Person struct. However, if the keys in the JSON data don't match the property names in our struct, we can use coding keys to specify the mapping.
Let's modify our Person struct to use coding keys:

struct Person: Codable {
    var name: String
    var age: Int
    var email: String

    enum CodingKeys: String, CodingKey {
        case name = "full_name"
        case age
        case email = "email_address"
    }
}

In this modified version of our Person struct, we've added an enum CodingKeys that conforms to the String and CodingKey protocols. Each case in this enum corresponds to a property in our struct. We've specified the mapping between the keys in the JSON data and the properties in our struct using the raw values of the enum cases.
Now, let's decode our JSON data using this modified struct:

let json = """
{
  "full_name": "John Doe",
  "age": 30,
  "email_address": "johndoe@example.com"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: json)

In this example, we've specified the mapping between the "name" key in the JSON data and the "full_name" property in our struct. We've also specified the mapping between the "email" key in the JSON data and the "email_address" property in our struct.

And we can also create a SwiftUI View to display the content of the parsed data.

struct ContentView: View {
    var body: some View {
        HStack {
            Image(systemName: "person.circle")
                .resizable()
                .scaledToFit()
                .frame(width: 50, height: 50, alignment: .center)
                .foregroundColor(.accentColor)
            VStack(alignment: .leading) {
                Text("\(person.name)")
                    .bold()
                    .font(.title)
                Group {
                    Text("\(person.age) years old")
                    Text("\(person.email)")
                }
                .font(.title2)
            }

        }
    }
}

In the example view above, we’ve created an HStack with a person image as the placeholder of the profile icon and a VStack containing the JSON data contents using string interpolation.

Coding keys provide a powerful way to specify the mapping between the keys in external data sources and the properties in our Swift structs. By using coding keys in SwiftUI, we can create more flexible and resilient apps that can handle a variety of data sources and formats.

That’s all of today’s post. I hope it helps and let me know if it is by leaving a comment. Don’t forget to subscribe to my newsletter if you’d like to receive posts like this via email.

I’ll see you in the next post!