How to parse JSON in Swift? (Codable: Parsing JSON Basics) - Part One

Note: If you are a beginner and you find it difficult to understand things written in this article. Feel free to ask questions on my Reddit page or Twitter.

Remember, you can do it. ; )


JSON to Codable

{
    "firstName": "Karan",
    "lastName": "Pal",
    "email": "karan@swiftpal.io",
    "id": 101
}
struct Contact {
    var firstName: String
    var lastName: String
    var email: String
    var id: Int
}

JSON is short for JavaScript Object Notation, and it is known for its ease of use and easy to read syntax for humans, but is it easy to use? Or is there something you can do to make your life easier while developing iOS Applications?

Codable is the solution to our difficulties. Codable is a type alias combined with two protocols.

  • Encodable

  • Decodable

These two protocols are Apple’s way of making our lives easy. They have done almost everything for us, and we just need to start parsing our JSON.

So, what do we need to do to start parsing our Contact JSON?

struct Contact: Codable { // Conform to Codable
    var firstName: String
    var lastName: String
    var email: String
    var id: Int
}

Can you even figure out what’s changed?

That’s right, Codable!

The only thing you need to keep in mind is your property name should match the key name in JSON. If you don’t want to follow this convention, don’t worry, continue reading, I am here for you.

Now we are ready to start parsing our Contact.

For demo purposes, let’s just consider our JSON is stored in a String.

let jsonString = """
{
    "firstName": "Karan",
    "lastName": "Pal",
    "email": "karan@swiftpal.io",
    "id": 101
}
"""

struct Contact: Codable {
    var firstName: String
    var lastName: String
    var email: String
    var id: Int
}

func parseContact() -> Contact? {
    do {
        let jsonData = jsonString.data(using: .utf8)!
        let contact = try JSONDecoder().decode(Contact.self, from: jsonData)
        return contact
    }catch {
        print(error.localizedDescription)
        return nil
    }
}

let contact = parseContact()!
print(contact.firstName)

Here’s what we did, we created a string with JSON in it.

Next, we created a Contact struct, which conforms to the Codable protocol and below that we created a function to parse our JSON and give us back the data as a Contact type.

Next, we parsed our contact and using dot notation print the firstName property.

You can copy and paste the above code in your playground and execute it.

It’s so easy, right? But have you met a backend developer whose way of declaring the schema is so ingenious that the first property is declared in Camel Case, the next in Pascal Case, and some of the rest in Snake Case?

If you haven’t, please open Google and below the search bar, click on “I’m Feeling Lucky.”

You unquestionably should start feeling lucky. Don’t be truculent about it in the comments section.

What should we do now? Follow the same convention in our schema?

Of course not.

Mystery CASE

OOPs, your JSON data just got changed.

let jsonString = """
{
    "first_name": "Karan",
    "lastName": "Pal",
    "email": "karan@swiftpal.io",
    "id": 101
}
"""

So, what should we do now?

Well, Apple already knows about our situation here and to solve our Mystery CASE, we will need to add an enum into our struct. So, let’s start with it.

struct Contact: Codable {
    var firstName: String
    var lastName: String
    var email: String
    var id: Int
    
    enum CodingKeys: String, CodingKey { // Our Saviour
        case firstName = "first_name"
        case lastName
        case email
        case id
    }
}

You can see the enum added in the above code is having all the four properties of the struct, but wait; there's something weird, the first case in our enum has a string value “first_name”, rest of the enums are left without a value.

So, if you don't know our dearest Swift that well, here's the explanation, Swift assigns the default value of the case depending on the primitive type declared by you next to the name of the enum.

In this case, the type is String, and this also means that if you don't specify a value, then Swift will automatically set the value of the case as the name of the case. E.g. the case lastName will be interpreted as case lastName = “lastName” .

Rest is handled by the CodingKey protocol to which the enum is conforming.

Wasn't it easy? We haven't explored the benefits of Codable entirely yet.

It's not over yet

In my next article, we will be learning in-depth about the two protocols from which the Codable is made, Encodable & Decodable, and handling null values.

If you have any suggestions or questions, Feel free to connect me on Twitter. 😉

Please Subscribe to stay updated about my upcoming articles and till then Keep Learning : )

If you haven't explored SwiftUI yet, Start exploring with your Pal.

Click here to read Part Two of this article.

Click here to learn SwiftUI.

How to parse JSON in Swift? (Encodable, Decodable, and handling Null values) - Part Two

SwiftUI - Build Your Second iOS App in Swift : Part Two