Working with JSON – Part 1

DISCLAIMER: In this series of posts you’ll learn to work with JSON, not with JASON, the evil character from Friday the 13th series. Besides, working with JSON has become a pleasure since Swift 4… while JASON keeps being mean. So, drop your hockey mask and start coding!

Basics

Let’s asume you have the following JSON file:

{
	"productId": 1423,
	"name": "Hockey Mask",
	"color": "white",
	"price": 39.90
}

You probably received this JSON response from an API request or you read a file content, which is a .json file. Either way, the common scenario is that you ended up having a Data type.

First, let’s create a Struct which contains our data structure:

struct Product: Codable {
    let productId: Int
    let name: String
    let color: String?
    let price: Float
}

The keyword here is Codable, which is a protocol. Actually it’s a protocol composition type since it contains two protocols: Encodable and Decodable. Basically, Encodable lets you convert a type back to an external representation (i.e. Data), while Decodable does the opposite thing.

In this example we want to convert from Data to Product, we could have used just Decodable. But later on we might want to do the other way around (i.e. send something back to an API, store the data in UserDefaults, etc). So let’s keep it as Codable.

Now, let’s convert our Data to Product:

let decoder = JSONDecoder()
if let product = try? decoder.decode(Product.self, from: jsonData) {
    print(product)
}
  1. We instantiate JSONDecoder, which “decodes instances of a data type from JSON objects“.
  2. We use option binding (instead of force unwrapping) to unwrap the result or fail gracefully. You may opt to use try and catch the errors the decoder might throw.
  3. Output the result.

Here’s what we get:

Product(productId: 1423, name: "Hockey Mask", color: Optional("white"), price: 39.9)

What’s next?

In the next post, you’ll learn how to deal with custom keys and custom objects.