Working with JSON in Swift

The following snippet shows how you can convert raw data to a JSON dictionary. Working with JSON in Swift isn't very convenient; many developers choose to use a library, such as SwiftyJSON, to work with JSON. We will not use anything; in order to understand what's going on when you load JSON from a web service, it's good to have done all the dirty work yourself at least once:

guard let data = data, 
        let json = try? JSONSerialization.jsonObject(with: data, 
               options: []) 
        else { return } 
 
    print(json) 

The preceding snippet converts the raw data to a JSON object. The print statement prints a readable version of the response data but it's not quite ready to be used. Let's take a look at how we can gain access to the first available movie in the response.

If you take a look at the type of object returned by the jsonObject(with:options:) method, you'll see that it returns AnyObject. This means that we will need to typecast the returned object to something we can work with, such as an array or a dictionary. When you inspect the JSON response we received from the API, for instance by using print to make it appear in the console, you'll notice that it's an array of movies. In other words, it's an array of [String: AnyObject], because every movie is a dictionary where strings are the keys and the value can be a couple of different things, such as Strings, Int, or Booleans. With this information, we can access the first movie's title in the JSON response as shown in the following:

guard let resultsArray = json["results"] as? [[String: AnyObject]] 
    else { return } 
 
let firstMovie = resultsArray[0] 
let movieTitle = firstMovie["title"] as! String 
print(movieTitle) 

As mentioned earlier, working with JSON in Swift isn't the most convenient thing to do. Because the JSON object is of the AnyObject type and we need to typecast anything we access, there's a lot of boilerplate code you will need to add. For the sake of learning, we won't use libraries for this throughout this book. However, if you're going to build your own apps that work with JSON, I recommend that you check out the SwiftyJSON library. The JSON reading code we saw earlier can be written in just a few lines with SwiftyJSON as follows:

let swiftyJSON = JSON(data) 
print(swiftyJSON["results"][0]["title"].stringValue) 

The library performs all of the typecasting for you so you can simply access string keys, array indexes, and extract values without trouble.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.182.96