Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

In this tutorial, I am going to show you how to Parse JSON in Swift 2 using the Class NSJSONSerialization. This is also referred to as Swift deserializing JSON, in a more layman terms it is referred to as How to read JSON in Swift.

This tutorial assumes that you have the JSON stored in a variable called data of type NSData. If you are looking for a way to access JSON from a website in Swift and also parse the JSON, check out some of the plugins that are available to get the JSON for you. We have included a small tutorial at the end of this using the Alamofire plugin. Have a look at Get JSON from URL in Swift

JSON Format

JSON stands for JavaScript Object Notation and is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. [ 1 ]

When you see JSON, it will look very similar to this (with different values):

    "id": 123,
    "name": "Jordan G",
    "age": 17

An object is an unordered set of name/value pairs. An object begins with the left brace { and ends with the right brace }. Each name is followed by a colon : and the name/value pairs are separated by a comma ,.

Below is a graphical representation of the above JSON format [ 3 ]:

JSON  object format

For more information on JSON and an in-depth look with examples, Check out .

Create a Class

In the habit of having nice, easily editable and convention tested code, we are going to create a Swift Class that will hold our method. This method will then hold our parse JSON code that we call call at any time. So here is the framework for that:

class OurJSONParser {
    function parseJSONResults() -> [String: AnyObject]? {
      /* This is where our code will go

Let’s parse JSON in Swift

Now you have an understanding of what a JSON object is and what the JSON format looks like we can start deserializing that JSON into Swift types.

This Swift 2 Parse JSON Tutorial assumes that you have at least a basic understanding of the Swift Programming Language and are generally comfortable with the basic syntax of Swift and are familiar with Xcode and its layout.

Error Handling

The first thing we are going to do is make sure that we handle any errors correctly, There is nothing more irritating to the developer and the user when there are errors and app crashed. In this example I am assuming that the user doesn’t really care about having the errors displayed to them so I am going to use a do-catch block and print the error to the console. Which syntax looks like this:

do {
    // stuff if works
} catch {
   // stuff if fails
   print("Error, Could not parse the JSON request")

Now, the rest of this code is going to be written in the do section of the above code.

The do-catch block in Swift handles errors which means that you do not need to pass an NSError pointer like you would in Objective-C.

Optional Binding

This is also a way to handle errors. Optional types, which handle the absence of a value say either “there is a value, and it equals x” or “there isn’t a value at all”. Using optionals is similar to using nil. We are going to use this method to unwrap the data, Why? Well, the value may be nil. You never what could happen, an app error, connection error, all sorts, it is better to be prepared. For this solution we are going to use an if statement:

if condition {
    // Do stuff
} else {
  // Do stuff
  print("No Data :/")

We do not need to use the else block with this statement as we don’t really need to do anything it it fails, but for the sake of this parse JSON in Swift tutorial I have added it in so that you will get a console output explaining an error.

As you can see above, the If-Else has condition – This is where we are going to say get the data if any has been returned and the result is not nil and assign it to a constant called data:

let data = data

We are also going to create another constant called json as part of the condition. We are also going to use try as it may throw an error and this will be of type NSJSONSerialization using the object JSONObjectWithData(). We will pass our constant data into the object as well. We also have the possibility to pass in options, but we will leave these empty for now.

json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]

If you want to know more about what options you can pass into this object, check out the NSJSONReadingOptions in the official Apple NSJSONSerialization Class Reference [ 4 ].

So far, our entire code should look like:

if let data = data,
 json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
    // Do stuff
} else {
  // Do stuff
  print("No Data :/")

As I mentioned above, there are possible options you can add options: []) but what is as? [String: AnyObject]. Well, as it sounds basically “As String” – What we are doing is converting the the JSON into a Swift Dictionary where they key of the dictionary is represented by a String and the value can be AnyObject.

Assuming that there are no errors and that we can assign everything to the JSON constant correctly, swift will then execute the rest of the if statement. This is where we will get the specific objects from the JSON.

Be sure to add the comma , after the data constant declaration.

This is achieved by simply assigning the returned data to constants or variable:

let id = json["id"] as? Int
let name = json["name"] as? String
let age = json["age"] as? Int

Now, all we need to do, is do something with the data. I will simple just print it out into the console for you to see the result.

print("Found User id: \(id) called: \(name) who is \(age) years of age")

Found User id: Optional(123) called: Optional(Jordan G) who is Optional(17) years of age

Wait, What are those Optional()s doing wrapping my output. This is because we simple just assigned the values straight to the constants with optionals. One way to solve this, and a bad way would be to use force type casting. However, you never know what the API will return so its better not to use that.

Instead we will do it like this:

if let id = json["id"] as? Int,
       name = json["name"] as? String {
    print ("Found User id: \(id) called \(name)")

This way, we only cast them IF it can find id and it can be made into an Integer AND if we can find name and it can be made into a String.

Get JSON from URL in Swift

As i mentioned above, This tutorial was to show you how to parse JSON in swift, not how to get JSON from url, The best solution for getting JSON from a URL in Swift is to use a plugin called AlamoFire, so without further delay, Introducing…

AlamoFire Json Parser

Alamofire comes from and is available on Github.

Download from GH

The following text is taken directly from their documentation and copyright stays with them, we added snippets here only to aid you with this swift tutorial to parse JSON in swift.

Making a Request

import Alamofire

Alamofire.request(.GET, "")

Response Handling

Alamofire.request(.GET, "", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")

Networking in Alamofire is done asynchronously. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are very good reasons for doing it this way.

Rather than blocking execution to wait for a response from the server, a callback is specified to handle the response once it’s received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler.


In this Swift 2 Parse JSON tutorial I have shown you a few things; Creating classes to hold our methods and code, How to use some basic error handling techniques to thwart any unforeseen errors, you should now be able to loop through and parse JSON and if not catch the error and display. I hope you liked the tutorial, stay tuned for me.

P.s Sign up to the mailing list below so you don’t miss out.


having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

Jordan Gregon

Written by:

Hey, I'm Jordan, i'm 17 from Atlanta, GA! Hoping you like my posts.