Swift – SwiftyJSON


Swift – SwiftyJSON



”;


What is JSON Data?

JSON is known as JavaScript Object Notation. It is a lightweight and most commonly used data interchange format that is easy to read and write. It is generally used to transmit data between a server and an application. JSON data is generally represented in key-value pairs. For example −


{
   "name": "Monika",
   "age": 23,
   "city": "Delhi"
}

Here name, age and city are the keys and Monika, 23 and Delhi are their respective values. In Swift, we can work with JSON data using the SwiftyJSON library.

SwiftyJSON

SwiftyJSON is a very important and powerful Swift library to handle JSON data in Swift programming language. It is commonly used to read and process JSON data returned by the APIs. It simplifies the process of parsing and working with JSON data in Swift easily by providing subscript syntax. It also provides various data types.

Before SwiftyJSON the developer faced various problems while working with JSON data in Swift and the problems were −

  • Verbose Syntax − Before the SwiftyJSON library the JSON data in Swift was handled by the JSONSerialization class which provides verbose syntaxes. Developers had to work with nested casting and a significant amount of optional unwrapping which makes code more complex and hard to read.

  • Type Safety − While handling JSON data Swift doesn”t provide any direct way to handle optional values or nested structures in a type-safe manner. The user has to either use conditional casting or manually check the presence of keys.

  • Readability − Reading and extracting values from the JSON was less readable. Swift doesn”t provide easy and clean syntax to work with JSON data.

  • Error-handling − The developer had to use the do-catch block to handle errors manually because Swift does not provide any straightforward method to handle errors for JSON parsing and extracting.

  • Lack of Convenience − Before SwiftyJSON developers had to write more boilerplate code to pars JSON data which makes the parsing more time-consuming.

These issues are later solved by the SwiftJSON library. It provides more expressive and straightforward methods to deal with JSON data in Swift.

How to use SwiftyJSON?

To use the SwiftyJSON library in your project you have to follow the following steps −

Step 1 − Install SwiftyJSON.

To install SwiftyJSON you can use either CocoaPods or Swift Package Manager. Here we will use Swift Package Manager. So Open Xcode project → go to File → Swift Packages → Add Package Dependency and then enter the following SwiftyJSON GitHub repository URL −

https://github.com/SwiftyJSON/SwiftyJSON.git

Now follow the prompts to add the package.

Step 2 − Now to use SwiftyJSON import the library at the top of the code using the import keyword.


import SwiftyJSON

Creating JSON Object: To create a JSON object SwiftyJSON provides the following initialiser.


let object = JSON(data: dataObject)
Or 
let obj = JSON(jsonObj) 

Accessing data − You can use subscripts to access JSON data.


// Getting string from JSON dictionary
let stdName = json[“name”].stringValue

// Getting int from JSON array
let value = json[1].int=

Iterating over an array or dictionary − SwiftyJSON supports a for-in loop to iterate over the elements of an array or dictionary.


// For array
for(index, element):(String, JSON) in json{
   Write something
}

// For dictionary
for(key, element):(String, JSON) in json{
   Write something
}

Example


import SwiftyJSON

// JSON string
let inputJsonString = """ {
   "name": "Mohan",
   "age": 40,
   "branch": "CSE"
}"""

if let jsonObj = inputJsonString.data(using: .utf8) {
   let x = try? JSON(data: jsonObj)

   // Accessing values using SwiftyJSON subscript syntax
   let name = x?["name"].stringValue
   let age = x?["age"].intValue
   let branch = x?["branch"].stringValue
   
   // Perform operations 
   print("Name: (name ?? "N/A")")
   print("Age: (age ?? 0)")
   print("Branch: (branch ?? "N/A")")
}

Output

This code will work on Xcode. It will not work on an online Swift compiler. −


Name: Mohan
Age: 40
Branch: CSE

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *