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 {
}





