JSON

This tutorial will teach us how to parse a JSON response in our iOS Application using JSONSerialization in Swift. We will discuss JSONSerialization with examples.

JSON – short for JavaScript Object Notation – is a way of describing data. It’s not the easiest to read yourself, but it’s compact and easy to parse for computers, which makes it popular online where bandwidth is at a premium.

JSON parsing in Swift is a common thing to do. Almost every app decodes JSON to show data in a visual way. Parsing JSON is one of the basics you should learn as an iOS developer.

Today, I’m going to show you how to parse JSON in your iOS app without using any 3rd party library.

There are are two ways to parse a JSON natively in iOS:

  • JSONSerialization: This is the old fashion way to parse JSON. It’s recommended only when you want to parse one or two JSON objects.
  • JSONDecoder: This method is available only in Swift 4 and later. You create your model and after parsing the JSON you’ll get an object with all the fields already filled.

JSONSerialization

Overview

You use the JSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

To convert a Foundation object to JSON, the object must have the following properties:

Other rules may apply. Calling isValidJSONObject(_:) or attempting a conversion are the definitive ways to tell if the JSONSerialization class can convert a given object to JSON data.

Before starting parsing let’s have a look at JSON Data.

{
  "blog_articles": [
    {
      "id": 309,
      "date": "2022-06-07T11:23:53",
      "modified": "2022-10-19T06:45:45",
      "status": "publish",
      "type": "post",
      "link": "https://appsquad.in/index.php/2022/06/07/tableview-custom-cell-with-xibnib/",
      "title": "TableView: Custom Cell Implementation With XIB(nib)",
      "description": "This tutorial shows how to implement a custom TableView Cell with XIB and show some real-time data in the TableView.",
      "post_image": [
        {
          "width": 1280,
          "height": 720,
          "url": "https: //appsquad.in/wp-content/uploads/2022/06/Chapter-2-1.png",
          "type": "image/png"
        }
      ],
      "author": "Ajharudeen Khan"
    },
    {
      "id": 300,
      "date": "2022-06-07T11:16:20",
      "modified": "2022-06-09T15:47:46",
      "status": "publish",
      "type": "post",
      "link": "https://appsquad.in/index.php/2022/06/07/tableview-custom-prototype-cell-implementation/",
      "title": "TableView: Custom Prototype Cell Implementation",
      "description": "In this article, will learn how to design and configure a custom prototype cell and show some real-time data on the Tableview using the Custom prototype cell. Before starting I assume you have some basic knowledge of TableView and how to create and use default prototype cells. ",
      "post_image": [
        {
          "width": 1280,
          "height": 720,
          "url": "https://appsquad.in/wp-content/uploads/2022/06/Chapter-2.png",
          "type": "image/png"
        }
      ],
      "author": "Ajharudeen Khan"
    },
    {
      "id": 267,
      "date": "2022-05-12T15:13:26",
      "modified": "2022-06-07T12:30:01",
      "status": "publish",
      "type": "post",
      "link": "https://appsquad.in/index.php/2022/05/12/tableview-basic-tableview-setup-and-configuration-in-swift/",
      "title": "TableView: Basic TableView Setup and Configuration in Swift",
      "description": "In this article, we will discuss basic TableView setup and configuration with a prototype cell and will show a genre list in TableView",
      "post_image": [
        {
          "width": 1280,
          "height": 720,
          "url": "https://appsquad.in/wp-content/uploads/2022/05/Property-Observers-in-Swift.png",
          "type": "image/png"
        }
      ],
      "author": "Ajharudeen Khan"
    }
  ]
}

This is the JSON data we are going to parse and will print the titles of all the blog posts.

var article_titles = [String]()

do {
    if let data = data,
        let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
        let blogs = json["blog_articles"] as? [[String: Any]] {
        for blog in blogs {
            if let name = blog["name"] as? String {
                names.append(name)
            }
        }
    }
} catch {
    print("Error deserializing JSON: \(error)")
}

print(names)

Let’s talk about the above code line by line.

First of all, declare an array type of String that holds article titles and initialise it with an empty string.

var article_titles = [String]()

The above JSON data either comes from the server or from the file in form of Data, So check the data first. Just understand that it’s a way to go from a Data? type (optional Data) to non-optional Data, keeping the same variable name. (This strange if-let syntax is called optional binding, and you need to understand it if you’re writing Swift. 

if let data = data {
    // code goes here
}

After that, we need to get JSONObject from the data with the help of JSONSerialization and cast that to a dictionary with String keys and Any values as [String: Any].

if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
    // code goes here
}

Don’t worry about the error we will discuss this later in this article.

let’s get the value of the key “blog_articles” that contains blog post information. Get the value from “blog_articles” from the JSON variable and cast it as an array of type dictionary with String keys and Any Values as [[String: Any]]

if let blogs = json["blog_articles"] as? [[String: Any]] {
       // code goes here
}

Instead of using multiple if statements combine all statements as below.

Now, let’s talk about the Error "Errors thrown from here are not handled". It’s because JSONSerialization.jsonObject(with:) method throws the error which we need to handle using the do...catch statement as shown below.

do {
     if let data = data,
       let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
       let blogs = json["blog_articles"] as? [[String: Any]] {
          // code goes here
    }
} catch {
     print("Error deserializing JSON: \(error)")
}

We got an array of the blog article in the blogs variable, it’s time to iterate the blogs array using for...in the loop and get the dictionary with String keys and Any values as shown below.

for blog in blogs {
}

In every iteration, we will get dictionary String keys and Any values as [String: Any]. Now the blog has all the information about the Blog Article for example "id", "date", "title", "description", "post_image" and so on.

We need to cast the title as String because the blog is the type of [String: Any].

if let title = blog["title"] as? String {

}

Now append the title in the article_titles array as shown below.

article_titles.append(title)
        var article_titles = [String]()

        do {
            if let data = data,
               let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let blogs = json["blog_articles"] as? [[String: Any]] {
                for blog in blogs {
                    if let title = blog["title"] as? String {
                        article_titles.append(title)
                    }
                }
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        print(article_titles)

This will print the blog titles in Console.

There are a couple of things that might confuse you there. First, because parsing JSON will fail if the JSON isn’t valid, you need to use try/catch and have some sort of error handling. Second, you need to typecast my example JSON to be a dictionary of type [String: Any] so that you can start working with your JSON values. Third, you don’t know for sure that any values exist inside the JSON, so you need to conditionally check for and unwrap the json, blogs and title value.

JSONDecoder and Codable protocol will solve all the confusion and make parsing a lot easier. We will discuss this in the next Article.

Summary

I hope this helps you to start working with JSON in Swift 3 — and furthermore, I hope you see that it’s relatively simple to do using the JSONSerialization class from the built-in Foundation framework. So many people seem to want to grab a third-party library to parse JSON, but for most use cases, I see very little benefit to using one to do something so simple. You don’t need a third-party library for everything.

Thank you very much for your precious time.

Hope you guys enjoy it.

Let me know your thoughts in the comment section.

Extend your knowledge

The Twitter contact:

Any questions? You can get in touch with me here

Leave a Reply

Your email address will not be published. Required fields are marked *