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!


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) {
  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.


  1. Pingback: online gambling the netherlands

  2. Pingback: cheap viagra 50mg

  3. Pingback: canadian pharmacy generic cialis

  4. Pingback: cialis 20mg 60

  5. Pingback: buy viagra 100 mg

  6. Pingback: onbling casino

  7. Pingback: interactions for viagra

  8. Pingback: viagra for women

  9. Pingback: buy cialis pills

  10. Pingback: cialis dosage recommend

  11. Pingback: order viagra 50 mg

  12. Pingback: cialis cost 20mg

  13. Pingback: cialis online canada

  14. Pingback: walgreens cialis prices

  15. Pingback: where to buy real viagra cialis online

  16. Pingback: extra super viagra

  17. Pingback: goodrx gold

  18. Pingback: zithromax dosing

  19. Pingback: sildenafil and tadalafil combination tablets

  20. Pingback: sildenafil price india

  21. Pingback: meloxicam lamotrigine lidocaine cream

Comments are closed.