Search Your Question

Json serialization and deserialization

Ans :  

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.

import UIKit

var str = "Hello, playground"

// Starting decode -> json to class or object
// ------------- De-Serialization ----------------

let singleDict = """
    "foodName" : "Banana"
    "calories" : 100
""".data(using: .utf8)

class Food: Codable {
    let foodname : String
    let calories : Int
    init(foodname: String, calories: Int) {
        self.foodname = foodname
        self.calories = calories

let jsonDecoder = JSONDecoder()
do {
    let foodResult = try jsonDecoder.decode(Food.self, from: singleDict!)
} catch {
    print("failed to decode \(error.localizedDescription)")

// Starting encode -> class or object to json
// ------------- Serialization ----------------

let apple = Food(foodname: "apple", calories: 80)
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
do {
    let jsonData = try jsonEncoder.encode(apple)
    if let jsonString = String(data: jsonData, encoding: .utf8) {
} catch {


What is Codable?
Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.

Before Swift 4, You’d have to serialize the JSON yourself with JSONSerialization, and then typecast every property of the JSON to the right Swift type. We have to do manually map data with struct (Model) properties.
If we are using Codable, then we don't required to map response data with struct property manually. If response's name is different then we can use CodingKey

struct User:Codable 
    var firstName: String
    var lastName: String
    var country: String

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case country

If you have any comments, questions, or recommendations, feel free to post them in the comment section below!

1 comment:

  1. We should use structure when creating a model. It is recommended by apple documentation