Using JSONEncoder

JSONEncoder will encode instances of types that conform to the Codable typealias, as JSON objects. The following code illustrates how to do this:

let book1 = Book(name: "Mastering Swift 3", author: "Jon Hoffman", publisher: "Packt Publishing") 
 
let encoder = JSONEncoder() 
let data = try? encoder.encode(book1) 

This code starts off by creating an instance of the Book and JSONEncoder() types. Next the encode method of the JSONEncoder is used to encode the Book instance to a JSON object. If the encode method fails it will return nil; otherwise it will return an instance of a Data object. We can convert this object to an instance of the string type as shown in the following code:

if let data = data, let dataString = String(data: data, encoding: .utf8) { 
  print(dataString) 
} 

This code uses optional binding to JSON data to a string type and then prints it to the console. The default format for this JSONEncoder is to compact the JSON object; therefore, the output would look like this:

{"name":"Mastering Swift 3","author":"Jon Hoffman","publisher":"Packt Publishing"}

If we would like this output to be formatted, automatically, into a format that displays better, we can set the outputFormatting property of the JSONEncoder instance like this:

encoder.outputFormatting = .prettyPrinted 

With this property set the output now looks like this:

{
  "name" : "Mastering Swift 3",
  "author" : "Jon Hoffman",
  "publisher" : "Packt Publishing"
}  

We would encode an array of Book instances exactly like the previous example except that, instead of passing an instance of a Book type to the encoder; we pass an array of Book types. The following code illustrates this:

let book1 = Book(name: "Mastering Swift 3", author: "Jon Hoffman", publisher: "Packt Publishing") 
let book2 = Book(name: "Mastering Swift 4", author: "Jon Hoffman", publisher: "Packt Publishing") 
 
let books = [book1, book2] 
let encoder = JSONEncoder() 
let dataEncoder = try? encoder.encode(books) 
if let data = dataEncoder, let dataString = String(data: data, encoding: .utf8) { 
  print(dataString) 
} 

Now that we have seen how to encode JSON objects with the JSONEncoder type, let's look at how we can decode JSON objects with the JSONDecoder type.

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

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