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() method of the JSONDecoder object is then used to decode the jsonData object. The first property of this method (Book.self) is the object type that we are decoding to. The second method is the Data object that we are converting from. If the decode() method fails it will return nil. If everything was successful the output of this code will look like this:

Book(name: "Mastering Swift 3", author: "Jon Hoffman", publisher: "Packt Publishing")  

Decoding an array of Book instances is very similar. The only difference is that we change the type of object we are decoding to, from Book.self to [Book].self. The following code shows how to do this:

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

Using the Encoder and Decoder types makes it very simple to convert to/from JSON objects. Starting with Swift 4 this is the preferred way to do these conversions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset