Use of Codable with JSONEncoder and JSONDecoder in Swift4

suggest change

Let’s take an example with a Movie structure. Here we have defined the structure as Codable, so we can encode and decode it easily.

struct Movie: Codable {
    enum MovieGenere: String, Codable {
        case horror, skifi, comedy, adventure, animation
    }
    
    var name : String
    var moviesGenere : [MovieGenere]
    var rating : Int
}

We can create an object from Movie like this:

let upMovie = Movie(name: "Up", moviesGenere: [.comedy , .adventure, .animation], rating : 4)

The upMovie contains the name “Up” and its movie genres are comedy, adventure, and animation, which is a rating of 4 out of 5. jsonString! below crashes if the UTF-8 string cannot be created.

Encode

JSONEncoder is an object that encodes instances of a data type as JSON objects. JSONEncoder supports the Codable object.

// Encode data
let jsonEncoder = JSONEncoder()
do {
    let jsonData = try jsonEncoder.encode(upMovie)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print("JSON String : " + jsonString!)
}
catch {
}

JSONEncoder will give us the JSON data which is used to retrieve JSON string.

Output string will be like :

{
  "name": "Up",
  "moviesGenere": [
    "comedy",
    "adventure",
    "animation"
  ],
  "rating": 4
}

Decode

JSONDecoder is an object that decodes instances of a data type from JSON objects. We can get the object back from the JSON string.

do {
    // Decode data to object
    
    let jsonDecoder = JSONDecoder()
    let upMovie = try jsonDecoder.decode(Movie.self, from: jsonData)
    print("Name : \(upMovie.name)")
    print("Rating : \(upMovie.rating)")
}
catch {
}

By decoding the JSON data we will receive the Movie object back, so we can get the values that are saved in that object. jsonData is the value produced by the encoder above; this snippet only sees it when both are in the same scope.

Output will be like:

Name : Up
Rating : 4

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents