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

Using JSONDecoder

The JSONDecoder type will decode instances of the data type from JSON objects to types that conform to the Codable typealias. The following code illustrates how to do this:

var jsonString = """ 
{ 
  "name" : "Mastering Swift 3", 
  "author" : "Jon Hoffman", 
  "publisher" : "Packt Publishing" 
} 
""" 
if let jsonData = jsonString.data(using: .utf8) { 
  let decoder = JSONDecoder() 
  let objs = try decoder.decode(Book.self, from: jsonData) 
  print(objs) 
} 

This code starts off by defining a string instance that represents the JSON data for a Book type. The string instance is then converted to an instance of the Data type using the data(using:) method. If the conversion is successful, an instance of the JSONDecoder type is created.

The decode() ...

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