<

Parsing JSONs in Swift with SwiftyJSON

Published on
4,692 Points
1,592 Views
1 Endorsement
Last Modified:
     Intro
     In this article, I will show you how to parse a JSON in Swift using an open source library called SwiftyJSON. If you haven't heard of a JSON before, it stands for JavaScript Object Notation and it is used to transfer data, usually between servers and applications. In other words, you will be using JSON in order to store any non-local data in your apps.  JSON is easy for people  to read and formatted so that it is easy for a computer to parse.
 
     Grabbing the info:
     In order to parse a JSON, you need to have some NSData to begin with. The most common place to get NSData is from websites. In order to do this you need to first create an array for storing the data. In addition to this we can set up our URL connection by creating a new NSURLConnection and passing it a NSURLRequest with your specified path.
var request: NSURLRequest = NSURLRequest(NSURL(string: <your url path>))
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)

var data: NSMutableata = NSMutableData()

Open in new window

Now you must implement a few methods that will be called when a response is received, when data is being appended, and when the connection is done loading data.

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // clear the array for new data to be loaded
   data = NSMutableData()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // appending data to array
   data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
   // anything that you want done after data loads
}

Open in new window

The first method is called when the connection receives a response. In our case this will be right when the connection is created because we set the startImmediatly parameter to true. If this was set to false, then you would need to start the connection explicitly by making an asynchronous or synchronous call to the connection by placing this line (or one similar) where you want the connection to start. I did not add any parameters to the call because there are so many variations on the method; you will need to choose which one best suits your needs.


NSURLConnection.sendAsynchronousRequest()

Open in new window


The second function is called while the connection is still open and will continue to append the data to your array. The final function is called when the connection is done loading. In our example this does nothing, but you may want to do something special when your data is done loading. 


Parsing the info

Now you finally have an array of data. Typically, there will be only one set of data from the URL that will hold all the important information. Now you will make a new JSON object by passing your data along to the constructor.
let json = JSON(data : data[0])

Open in new window

 Alternatively you could loop through your array of data if you had more than one instance of data. Now comes the easy part: actually accessing the elements. Given an example JSON from json.org:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        }
    },
    "required": ["id"]
}

Open in new window

Say you wanted to access the title:

let title = json["title"].stringValue

Open in new window

or the description of the id:

let description = json["properties"]["id"]["description"]

Open in new window

or the required array (it only contains one thing but the [] signify an array):

let requiredArray = json["required"].arrayValue

Open in new window

or if we just wanted the first element:

let requiredArrayFirstValue = json["required"][0]

Open in new window


If it weren't for SwiftyJSON, each time we wanted to access something in our JSON, it would require an if statement for each level into the hierarchy that you reach. This makes your code ugly fast. SwiftyJSON helps to clean up your code vastly and makes it much more readable.
1
Comment
0 Comments

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Join & Write a Comment

When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
Overview of OneDrive and collaboration.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month