A Handy Guideline On Using JSON In Swift

Tutorials No Comments

Data organization and access are two of the most crucial parts of any web development project. Thanks to the unstoppable advancements in the field of web technology, today we have numerous tools that can help us in organizing and accessing data in a flawless format. JSON is one such incredibly effective tool that  is simple to use and serves as a brilliant means for transmitting data to and from the web services. As you read through this post, you’ll come to know about the exclusivity of JSON and the process of using it in the Swift programming language. So, get ready to grab every minute detail about JSON and its use in Swift.

 

What’s JSON?

Before heading towards the usage of JSON in Swift, I’d like to make you familiar with what JSON is. Well, JSON(JavaScript Object Notation) is basically a light-weight data interchange format that’s easy for human beings to read and write. Based on a subset of JavaScript programming language, JSON is completely language independent but uses all the conventions that have been set for the C, C++, C#(Sharp), Perl, Java, JavaScript and Python programmers.

 

A sneak peek into parsing and de-serializing JSON in Objective C

For example, here’s a JSON snippet:

[
“person”: {“name”:”Dani”,”age”:”24″},
“person”: {“name”:”ray”,”age”:”70″}
]

Well, the code snippet used for parsing and de-serializing JSON in Objective C is as shown below:

NSString *age = json[0][@“person”][@“age”];

NSLog(@“Dani’s age is %@”, age);

In this post, I’ll be using SwiftyJSON for parsing a JSON document. So, let me walk you through all the steps that are involved with the same:

 

Step 1- Download a starter project

Since a user interface isn’t of much an important, you’ll need to work with the console itself. The starter project comprises of a few files that allow you to keep your focus on the process of parsing JSON in Swift. Here’s a look at these files:

  • json- this file contains the JSON string that needs to be parsed.
  • DataManager- this file manages the data retrieval whether from local or an external network.
  • AppModel- this is the traditional Swift object that represents an app.
  • ViewController- this is an empty view controller where you’ll need to add the code for requesting data from DataManager.swift.

 

Step 2- Use the native way to parse JSON in Swift

Here, you can simply start by parsing JSON in the native Swift way i.e. without the use of an external libraries. For this, following the below steps is a must:

  • Open ViewController.swift and add the below mentioned code to the end of viewDidLoad():

DataManager.getTopAppsDataFromFileWithSuccess { (data) -> Void in

 

// Get the number 1 app using optional binding and NSJSONSerialization

//1

var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.AllowFragments,
error:&parseError)

//2

if let topApps = parsedObject as? NSDictionary {
if let feed = topApps[“feed”] as? NSDictionary {
if let apps = feed[“entry”] as? NSArray {
if let firstApp = apps[0] as? NSDictionary {
if let imname = firstApp[“im:name”] as? NSDictionary {
if let appName = imname[“label”] as? NSString {
//3
println(“Optional Binding: (appName)”)
}
}
}
}
}
}
}

Step 3- Integrate SwiftyJSON into your project

In order to integrate SwiftyJSON into your project, all you need to do is simply go to the SwiftyJSON Github page and opt for downloading the library to a convenient location on your system. After this, simply drag SwiftyJSONSwiftyJSON.swift into your project in the Xcode. Here, ensure to select Copy items and check whether the TopApps target has been selected or not. Once it has been selected, click on the ‘Finish’ button.

Step 4-Using subscripts

It is interesting to note that an array structure in JSON is being wrapped into an Array<JSONValue> which denotes that everything available within the Array is actually a JSONValue. Therefore, in order to fetch the element’s value, you need to retrieve an array from JSONValue, as shown in the below mentioned lines of code:

if let array = json[“key_of_array”].array{
if let string = array[0].string{
//The array[0] is still a JSONValue!
}
}

The above code is applicable for Object as well. One of the best methods of accessing Arrays and Objects is to use the JSONValue’s subscripts as explained below:

if let string = json[“key_of_array”][0].string{
}

Moreover, you can always use these subscripts for accessing any JSONValue, without worrying about system crashes occuring due to runtime errors.

Step 5- Retrieve Remote JSON

Here, all you need to do is go to DataManager.swift and add the below mentioned method to it:

class func getTopAppsDataFromItunesWithSuccess(success: ((iTunesData: NSData!) -> Void)) {
//1
loadDataFromURL(NSURL(string: TopAppURL)!, completion:{(data, error) -> Void in
//2
if let urlData = data {
//3
success(iTunesData: urlData)
}
})
}

As per the above code, I’m using NSURLSession for pulling data from iTunes.

 

Wrapping Up

So that was an elaborate guideline on using JSON in Swift. Hope you’d have found the steps easy-to-follow and useful enough for executing your next project of utilizing JSON assets in Swift.

 

About Author

Emily Heming is a technical writer for Xicom Technologies a Mobile App Development Company from where you can also avail the facility to Hire iOS Developers with her best assistance.

We really appreciate you for visiting PremiumCoding and reading this article! Now you might also want to check out our Themes here.
PremiumCoding
Written by PremiumCoding
We develop beautiful Wordpress themes with minimal and clean design.