Working with JSON in Swift
The following snippet shows how you can convert raw data to a JSON dictionary. Working with JSON in Swift can be a little tedious at times, but overall, it's a generally good experience. Let's look at the following example:
guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) else { return } print(json)
The preceding snippet converts the raw data that is returned by a URL request 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 see how you gain access to the first available movie in the response.
If you look at the type of object returned by the jsonObject(with:options:)
method, you'll see that it returns Any
. This means that you must typecast the returned object to something you can work with, such as an array or a dictionary. When you inspect the JSON response that the API returned, for instance by using...