O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Encoding and Decoding JSON Data

Before we see how to encode and decode JSON data we will need to create a structure that will define the data we wish to encode from or decode to. In the examples for this section, we will create and parse a JSON document that contains a list of books. Let's define the Book structure like this:

struct Book { 
  var name: String 
  var author: String 
  var publisher: String 
} 

This structure contains three properties, which are the name, author, and publisher of the book. To use this structure with the encoder and decoder types, it will need to conform to the Codable typealias. Codable is a typealias for the Decodable and Encodable protocols. To make this type conform to Codable, we need to add it to the type definition ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required