Introduction: Codable is a protocol added in Swift 4 which provides a simple and easy way to encode and decode JSON from its respective Swift objects. Coding is the process of converting objects between different representations, while decoding reverses the process. JSON (JavaScript Object Notation) is extensively used as a data format for communication between a server and a client, and Swift Codable helps us achieve this effortlessly, eliminating the need for manual parsing of JSON responses.
Coding Structure: The Codable protocol has two types, Decodable and Encodable. The Decodable protocol allows the model object to decode JSON, converting raw data to a Swift object, and Encodable protocol encodes the Swift object to a JSON object. The Codable protocol combines both the Encodable and Decodable Protocol.
The following is a simple data model example:
struct Student: Codable {
var name: String
var rollNo: Int
}
The above code creates a model class Student with two properties, name and rollNo. The keyword Codable tells that the class conforms to Codable protocol.
JSON Encoding and Decoding: To decode JSON data into the Student class model, we can use the JSONDecoder() API. JSONDecoder() is used to convert JSON data to Swift objects, and we can access the data as shown below:
let studentStr = """
{ "name" : "John" , "rollNo" : "1234" }
"""
let studentData = studentStr.data(using: .utf8)!
let decoder = JSONDecoder()
do {
let studentDetails = try decoder.decode(Student.self, from: studentData)
print(studentDetails.name)
print(studentDetails.rollNo)
} catch let parsingError {
print("Error", parsingError)
}
In the above code, we pass JSON data as a string then using JSONDecoder(), we convert the data to swift object by using the following line of code
let studentDetails = try decoder.decode(Student.self, from: studentData)}
To encode the Swift object to JSON data, we can use the JSONEncoder() API. We can pass any object to JSONEncoder().encode() method, which returns Data, then we can get the data in JSON format by using data's .utf8 property.
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(studentDetails)
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString!)
} catch let error{
print("Error: \(error)")
}
Conclusion: Swift Codable is an easy and effective way to parse JSON data in Swift. It saves the developer from the burden of manual parsing of JSON data, making JSON encoding and decoding a lot simpler. In just a few lines of code, we can quickly parse and manipulate data, enabling us to write efficient and high-performance code.