Swift 4 decoding JSON using Codable

2018-06-18 09:22 AM

231

Swift 4 was released along with iOS11 last September. It focuses on improving the stability of the ABI (application binary interface).

Introduction

This meant less drastic changes as compared to when we made the move from Swift 2 to Swift 3. My favourite new feature in Swift 4 is the addition of the Codable extension. Codable makes it easy to parse JSON into structs and use throughout your code, no more messing around with dictionaries. Swift 4.1 makes some changes to the Codable extension that make it even more powerful, but more on that later.

Prerequisites

It’s not a requirement but cloning the completed example project may make the tutorial easier to follow. Example Project

Main content

Understanding your JSON

For this tutorial I will be reading in JSON from a local file. The principles of using the Codable extension do not change whether you are reading in data from a local file or one on a server.

The stub data within the project contains a file londonWeather.json This is a real response from the open weather map API.

There are two key concepts in understanding your JSON file: you need to understand what is a key/value pair and what is a key/object pair. The stub data contains plenty of examples of either of these. If we look at the highest level of the object the first two keys are examples of key/value.

"id":2643743,
"name":"London"

The key maps directly to the value, key being the string on the left of the colon and the value being the type (such as string integer) on the right.

Key/object pairs are those that don’t map directly to types in JSON. The object itself usually contains a set of key/values.

"coord": {
"lon":-0.13,
"lat":51.51
},

The key in the above example is coord but within the object there are two key/value pairs. Another example of a key/object pair is one that maps to an array. The principle is the same here but it can map to more than one object.

1 – You must make sure that the struct conforms to the Codable protocol.
2 – The variable coord maps to a key/object pair in the JSON. You will need to create a new structure that also conforms to Codable called Coord. More on this below.
3 – The variable weather maps to an array of objects in the JSON. WeatherDetails is a struct that also conforms to Codable.
4 – The variable base maps to a key/value pair.

When we decode the JSON, Codable will map each of the variable names to the keys in the JSON and assign the value to it. If the key contains an object, it will dive down into the struct and decode that as well. For example Coord is another struct that conforms to Codable:

struct Coord: Codable {
let lon: Double
let lat: Double
}

It’s that simple to set up your basic structs to conform to Codable. You need to make sure that your type matches the one the JSON will supply, such as String, Double (for floating points), Int and so on.

Variable names using coding keys

It’s important to make sure that your variable names match to that of the keys within the JSON. This makes Codable simple to use in cases where we don’t care how the Swift variables are named, but that’s a rarity. JSON styling tends to prefer snake case whereas Swift tends to be camel case. We can extend Codable to use Coding Keys. We can use these to map the key within the JSON to our own variable name.

When we do this we have to include all the keys whether we are mapping them or not. We also have to include the init and encode functions that can be found within the Main.swift file in the example project.

Variables, constants and optionals

The example project has set everything to be a constant (let). It’s important to note that we can also set them to be variables if we are going to be manipulating the variables at a later date.

Understanding your API end point is also important, understanding whether keys will always be present or only in certain circumstances. Codable will fail to parse the JSON if it searches for a key that it’s expecting but does not find it. This will result in none of the data being available so we want to avoid this wherever possible. We can use optionals (more detail on optionals can be found here) to tell Codable that something may or may not exist when we decode the JSON.

let tempMin: Double?

If you’re using coding keys remember to replace:

values.decode(Double.self, forKey: .humidity)

With:

values.decodeIfPresent(Double.self, forKey: .humidity)

If you are using optionals.

Decoding the JSON

Now we need to retrieve the JSON from the remote server and convert the data into our structures. To do this create an APIManager that will handle requests to end points and return objects.

1 – Calls a function passing a URL that will return a Data object. The logic in this function is a standard URLSession request.
2 – A call to a function that will convert the data to our CurrentWeather object. Shown below:

1 – Setting the decoder to use a coding strategy convertFromSnakeCase will mean that Codable will automatically map our camel case variables to the JSON snake case variables.
2 – This is where we try to convert our data using the JSONDecoder. We tell the decoder what we are trying to convert the JSON to. In our case this is CurrentWeather.self. This is the high level struct that we created earlier. We also need to provide the data object (json).
3 – If we haven’t set up our structs correctly, for example including a variable that isn’t in the data and isn’t considered optional or providing an incorrect type the decoder will fail. This will throw an error that we can catch here for debugging purposes.

We should be aware that because the JSON decoder can throw an error our object will be an optional. We can assign it to a non optional within the controllers that we wish to use it.

We return the error from the API manager to here as well so that we can tell the user something has gone wrong. Note that error is optional so it won’t necessarily exist here. Otherwise we have our weather object that we can unwrap using a guard and if we wish assign it to a variable within the class.

Conclusion

Codable is powerful in helping us decode (and also encode) JSON, it makes it quick and simple to get data from an API. The thing you have to do is understand your JSON data. Knowing what is optional/non-optional and whether something is a String, Double or Int before you get started can save you lots of time in the long run and reduce your number of bugs.