Swift: Simplify JSON decoding: using Codable

When you’re making many API calls in your app, and your response objects are of a consistent structure, it is very convenient to have the response data automatically mapped into Swift objects. Codable introduced with Xcode 9, iOS 11 and Swift 4, makes that possible.

Here’s an example JSON document for a Book

{
    "name": "Swift Essentials",
    "rating": 9.2,
    "author": "Dr. Alex Blewitt",
    "publisher": "O’Reilly",
    "language": "swift"
}

Create a data structure for this, and be sure to mark them as Codable.

enum Language: String, Codable {
    case Java
    case Swift
}

struct Book: Codable {
    var name: String
    var rating: Double
    var author: String
    var publisher: String
    var language: Language
}

Now for the actual decoding, we need to create a decoder…

let decoder = JSONDecoder()

…and decode it.

let jsonData = jsonString.data(encoding: .utf8)!
let book = try! decoder.decode(Book.self, for: jsonData)

That’s it! We have parsed our JSON data into a Book instance. It didn’t require more than 2 lines of code. Please note that in your code you should catch errors and handle them appropriately.

 

 


Also published on Medium.

By |2019-04-02T17:09:37+00:00March 14th, 2019|Categories: iOS Tutorials|Tags: , , , |0 Comments

Leave A Comment