JSON Serialization/Deserialization in Swift 4

Gurwinder Singh
2 min readAug 31, 2019

--

JSON Serialization in Swift

What is JSON?
JAVA Script Object Notation, Basically annotation to Object, JAVA for Serialization(Convert object into byte for Storage).

Swift core Libraries for Serialization

  • Encodable
  • Decode

Code Snippet for Encodable

Encodable

struct LogInRequest: Encodable{

var emailId : String

var contactNo: String

var password: String

var name: String

var deviceToken: String

var deviceType: Int

var loginType: Int

var facebookId: String

var operatorToken: String

}

Encodable protocol in Swift for to encode the object in byte with Specific Encoding, so that it can be easily decodable in Specified Format like (UTF-8).

Method to Encode the class /Struct with encodable protocol

try JSONEncoder().encode(LogInRequest(

emailId: “”,

contactNo:pContactNo,

password: “”,

name: “”,

deviceToken: pDeviceToken,

deviceType: 0,

loginType: 0,

facebookId: “”,

operatorToken: pOperatorToken

)

)

It also must to be enclose in Try/catch block, because it always throws an exception if it failed to encode the object of class.

Decodable

struct LogInResponse:Decodable {

var status: Int?

var contactNo: String?

var emailId: String?

var sessionToken: String?

var referalCode: String?

var message: String?

}

Method to decode the Serialised JSON String and parse into Specific Type Object. In Android, it’s very easy to decode the String into JSON using Gson Library.

Swift Core functionality to decode JSON.

var pLogInResponse:LogInResponse!

pLogInResponse = try! JSONDecoder().decode(LogInResponse.self,

from: pString!.data(using:.utf8)!

)

It also must to be enclose in Try/catch block, because it always throws an exception if it failed to decode the object of class.

Its easy to parse the data using

JSONDecoder().decode(<Type of class>, from: NSDATA(JSON STRING)

Hope its very easy and simple example to understand the JSON Serialization and Deserialization of Object.

Thank you Learning, for further understanding to clear the concept, Clap and following MY MEDIUM BLOGS.

--

--

Gurwinder Singh

Full Stack Mobility Senior Software Developer in PayPal , Ex-PayTM, Ex-Jugnoo Taxi. For a deep understanding of the coding concept, follow my blogs.