How to parse JSON object in iPhone/iOS?


JSON stands for Javascript object notation. Most of the when dealing with APIs or any other services the data is returned in JSON format and we need to convert it to usable and supporte language formats.

Foundation framework of iOS provides a class JSONSerialization to convert JSON into supported formats like Dictionary, strings, Bool etc.

The JSONSerialization class provides a method jsonObject(with:options:) that parses json and returns Any as result, and an error if the data cannot be parsed.

// Example JSON:
/*
{
   "age": 42.0,
   "name": {
      "firstName": “tut”
   }
}
*/

Let’s see this with help of another example, let’s suppose we got data from our API call, now to parse this data we’ll use JSONSerialization. jsonObject(with:options:)

if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { }

// Now the above json object contains the received data as a dictionary of String and Any, or it goes out of if let block to else

// suppose json contains a key “Student” and value associated with that is a dictionary

guard let student = json[“Student”] as? [String: Any] else { return }

This is how we can parse json and get value from it. We can further enhance this using models and initializers. Let’s see an example of this by creating a local json file and then trying to parse it.

Let’s create a json file with following data and save it as exercises.json

{
   "Warmup": {
      "Exercises": [
         {
            "Name": "Neck Strech",
            "images": [
               "http:sdf.com",
               "sdf",
               "sdf",
               "sdf"
            ],
          "time": 30
         }
      ]
   }
}

We’ll parse this local json now and print the result using following code −

if let filePath = Bundle.main.path(forResource: "exerciseData", ofType: "json") {
   do {
      let data = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe)
      let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
      if let exercises = jsonResult as? [String:AnyObject] {
         if let warmups = exercises["Warmup"] as? [String:AnyObject] {
            print(warmups)
         }
      }
   } catch {
      print(error.localizedDescription)
   }
}

When we run this code, below is the output that we get.

Updated on: 27-Jun-2020

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements