Table of contents
1.
Introduction
2.
Swifty JSON and Problem with JSON in Swift
2.1.
Problem with JSON in Swift
2.2.
Download SwiftyJSON
2.3.
Example of using JSON with SwiftyJSON
3.
Parsing and Using SwiftyJSON
3.1.
Getters
3.1.1.
Non-Optional
3.1.2.
Optional
3.1.3.
Dictionary/Array
3.2.
Error Handling
3.3.
Merging Separate JSON
4.
Frequently Asked Questions
4.1.
What does JSON stand for?
4.2.
Do we need any separate text editor to edit JSON files?
4.3.
Mention some of the uses of JSON.
4.4.
Why does someone prefer JSON over XML?
5.
Conclusion
Last Updated: Mar 27, 2024

Swifty JSON

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

For an OS developer, data is the essential requirement as to what is the meaning of an operating system without data. As if they will not collect data, then the user will not be ab;e to get regular updates according to their requirements and many more. Without data, how will the developer know the requirements?

So till now, we have understood that data is necessary for OS developers. So how do they get the data? The answer is from the JSON files. To process and analyze data, we mostly use JSON files. We use Swift for IOS. But using JSON directly with Swift creates some problems for developers that SwiftyJSON resolves. We will learn all about the difficulties developers face while using JSON in Swift and SwiftyJSON, so we will not waste any further time and get on with our topic.

Swifty JSON and Problem with JSON in Swift

SwiftyJSON library is an open-source library that helps process and read JSON data from API/Server.

We can also use Swift for JSON, but Swift is very strict about its data types, and the user has to declare them explicitly. This will create a problem.

SwiftyJSON was built to remove the need for optional chaining in regular JSON serialization.

Problem with JSON in Swift

Here, we will discuss the mess or problems faced by the user while dealing with JSON in Swift. Suppose you want to get the list of student names from your JSON data. If you use JSON in swift, it will look like this:

if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
    let students = statusesArray[0]["students"] as? [String: Any],
    let studentName = user["name"] as? String {
    //we got the student name
}

As you can see, it seems pretty complex. NOw for SwiftyJSON, it will look like this: 

let json = JSON(data: dataFromNetworkingOrString)
if let studentName = json[0]["students"]["name"].string {
  //we got the student name
}

See, it has become so much more straightforward than the previous one.

Download SwiftyJSON

You can clone or download SwiftyJSon directly from their GitHub repository.

Example of using JSON with SwiftyJSON

In this example, we will learn how to use JSON with SwiftyJSON.

Here is a sample JSON:

let json = "{ \"people\": [{ \"firstName\": \"Peter\", \"lastName\":\"Parker"\  \"firstName\": \"Tom\", \"lastName\":\"Holland"\ ] }"

In the above JSON file, we have 2 names both containing first and last names. To print the last name of all the people in the above JSON file we can write the following code:

if let data = json.data(using: .utf8) {
    if let json = try? JSON(data: data) {
        for item in json["people"].arrayValue {
            print(item["lastName"].stringValue)
        }
    }
}

Sometimes JSON can have some nested dictionaries shown below:

{  
   "metadata":{  
      "responseInfo":{  
         "status":200,
         "developerMessage":"OK",
      }
   }
}

Before moving forward check the status code 200:

if json["metadata"]["responseInfo"]["status"].intValue == 200 {

 
}

Parsing and Using SwiftyJSON

First, download the latest version from the git repository, drag your “swiftJSON.swift” file into your project, and import it into your class.

import SwiftyJSON  
You can create your object by any of the two methods given below
let jsonObject = JSON(data: dataObject)  
Or
let jsonObject = JSON(jsonObject)
You can also use subscripts to access your data
let nameOfFirstObject = jsonObject[0]["name"]  
let firstObjectInAnArray = jsonObject[0]  

Getters

You can get optional and non-optional data in SwiftyJSON. You can also get Dictionary and Array.

Non-Optional

You can get the non-optional data you have to set data+type as shown below:

let studentname = json["students"]["name"].stringValue //for string
let hasAttended = json["students"]["hasAttended"].boolValue //for boolean
let id = json["students"]["id"].intValue //for integer

Optional

To get optional data you just have to set the type like shown below:

let studentname = json["students"]["name"].string //for string
let hasAttended = json["students"]["hasAttended"].bool //for boolean
let id = json["students"]["id"].int //for integer

Dictionary/Array

You can get a dictionary and array as shown below:

let list: Array<JSON> = json["list"].arrayValue // If not an Array or nil, return []
let user: Dictionary<String, JSON> = json["user"].dictionaryValue // If not a Dictionary or nil, return [:]

Error Handling

There is a specific types of errors in JSON that can make your app crash, and those are:

  • The app may crash when the index is out of bounds for an array.
  • If it is not a dictionary, not an array, the app will crash.
  • For a dictionary, it will be assigned to null without reason.

But it can take care of the eros by itself and can print its own errors shown below:

if let name = json[1339].string {  
    //You can use the value - it is valid  
} else {  
    print(json[1339].error) // "Array[1339] is out of bounds" - You cant use the value  
}  

You can also write your JSON object by using subscripts:

var originalJSON:JSON = ["name": "Tom", "age": 19]  
originalJSON["age"] = 25   
originalJSON["surname"] = "Naman" 

You can also get the original value of the raw string shown below:

if let string = json.rawString() { //This is a String object  
    //Write the string to a file if you like  
}  
if let data = json.rawData() { //This is an NSData object  
    //Send the data to your server if you like  
}  

Merging Separate JSON

Suppose you are getting different data from many APIs, and you want to collect and analyze all of them to give the corresponding result. Then you need to merge different Json files together. In SwiftyJSOn, you can do the merging by using the .merge function shown below:

let update: JSON = [
    "lastname": "Doe",
    "age": 28,
    "skills": ["Cooking"],
    "address": [
        "street": "Kilowatt St",
        "city": "Davao City"
    ]
]
let original: JSON = [
    "firstname": "Francis",
    "age": 20,
    "skills": ["Coding", "Writing"],
    "address": [
        "city": "DVO",
        "zip": "8000",
    ]
]



 
let updated = original.merge(with: update)
// updated value is now
// [
//     "firstname": "Francis",
//     "lastname": "Fuerte",
//     "age": 28,
//     "skills": ["Coding", "Writing", "Cooking"],
//     "address": [
//         "street": "Kilowatt St",
//         "zip": "8000",
//         "city": "Davao City"
//     ]
// ]

Frequently Asked Questions

What does JSON stand for?

JSON stands for Javascript Object Notation.

Do we need any separate text editor to edit JSON files?

No JSON is a text-based format file, so you can edit it in any text editor like notepad.

Mention some of the uses of JSON.

Used for transmission of serialized data and display data, suitable with most programming languages, APIs use JSON.

Why does someone prefer JSON over XML?

JSON is faster compared to XML and has different data types, unlike XML, where all the data is in strings.

Conclusion

In this article, we have extensively discussed SwiftyJSON, and its benefits over JSON in Swift, followed by an example and step-by-step explanation of how to use and parse JSON with SwiftyJSON.

If you are not much comfortable with Swift yet and looking for a tutorial, don't worry; Coding Ninjas has you covered. To learn, see Swift Tutorial for Beginners. 

Also check out - Data Dictionary In Software Engineering

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, React, JavaScript, System Design, etc. Refer to the mock test and problems; If you are looking for practice questions to enter in Tech Giants like Amazon, Microsoft, Uber, etc., you must look at the interview experiences and interview bundle for placement preparations. Do upvote our blog to help other ninjas grow.

Nevertheless, you may consider our paid courses to give your career an edge over others.

 “Happy Coding!”

 

Live masterclass