SwiftyJSON: How To Parse JSON with Swift

By Francis Fuerte and Chris Ching


swiftyjson

If you have been diving deep into iOS development you may have already come across accessing data/databases using URLSession, more so when you are trying to process data most especially JSON files, this is where SwiftyJSON comes in, So what is SwiftyJSON?

What is SwiftyJSON?

SwiftyJSON is a library that helps to read and process JSON data from an API/Server. So why use SwiftyJSON?

Swift by nature is strict about data types and wants the user to explicitly declare it. This  becomes a problem as JSON data is usually implicit about data types.

Lets say you want to get a list of student names in your JSON data. A typical Swift conversion of JSON data typically looks like this:

Looks even more confusing and is prone to mistakes, yikes!.

However, with the use of SwiftyJSON the codes above will only look like this:

See how easy that was? Easy to read and easy to write πŸ™‚

Part 1: Installation

You need to have cocoapods installed for this, once that is ready, let’s create our xcode project. For this example we have created an xcode project called SwiftyJSONTest.

We're going to need the SwiftyJSON pod in order to use SwiftyJSON
We’re going to need the SwiftyJSON pod in order to use SwiftyJSON

Now navigate to your project folder and open a terminal window, also navigate the terminal window to the project location.

Navigate to your project folder via Terminal and type pod Init
Navigate to your project folder via Terminal and type pod Init

Once there you should do a β€œpod init” in your terminal

It will then output a file named Podfile.

Open the podfile and add the SwiftyJSON pod
Open the podfile and add the SwiftyJSON pod

Open the Podfile in Textedit and add the line pod β€œSwiftyJSON”, β€œ[version number]” or just simply pod β€œSwiftyJSON”

Save the file and in your terminal do a pod install, once it has finished installation it should have created a Pods folder, [projectname].xcworkspace, and a Podfile.lock.

Run pod install and open the xcworkspace file.
Run pod install and open the xcworkspace file.

Open the file named [projectname.xcworkspace] and your project should have SwiftyJSON installed and ready to go

Open the xcworkspace project file
Open the xcworkspace project file

Part 2: Using SwiftyJSON

The Basics

For this example we will be using httpbin.org’s JSON functionality to simulate our JSON response. We will also be using the pod Alamofire 5 to make out http calls easier.

Our sample json response from httpbin looks like this:

Here's some sample JSON
Here’s some sample JSON

For starters let’s start with a basic SwiftyJSON call getting the title of the slideshow:

Here's SwiftyJSON in action
Here’s SwiftyJSON in action

The debug print looks like this:

Printed output
Printed output

Getters

SwiftyJSON has an option of getting optional and non-optional data and is quite straightforward. It also supports getting Array or Dictionary values.

Optional

For getting optional data you just need to simply set the type, for example:

Non-Optional

For getting non-optional data you just need to simple set the type + value, to better illustrate:

Array/Dictionary

Getting Array or Dictionary values is also easy:

Exists

Typically, you might want to check a particular data exists in your json response, to do so just simply:

Error Handling

Typically your app will crash If the JSON is:

  • an array, the app may crash with “index out-of-bounds.”
  • a dictionary, it will be assigned to nil without a reason.
  • not an array or a dictionary, the app may crash with an “unrecognised selector” exception.

However, this is automatically handled by SwiftyJSON making it not only convenient, but also practical to use, check out these examples to illustrate:

Data Handling with Iteration

We have covered the basics and features of SwiftyJSON but have yet to use it normally. Luckily, our sample data set has an attribute called β€œslides” that we can call and practice real world calls/iteration with.

Working with Arrays

We can break down and map our JSON data by putting it in arrays. To do so just simply get the .arrayValue of JSON and then map the data like so:

Working with arrays using SwiftyJSON
Working with arrays using SwiftyJSON

These lines of code will result into this:

printed output
printed output

See how easy it was to map? You now workable arrays of your JSON data to work with.

Working with Dictionaries

Handling data in as a Dictionary is relatively easy, you can use the built-in for function to iterate over keys and data/values from your JSON result like so:

Working with dictionaries using SwiftyJSON
Working with dictionaries using SwiftyJSON

These lines of code will result into this:

printed output
printed output

Super simple and does the trick! It even automatically handled the first element having no β€œitems” and just simple set it as null, how cool was that!

Merging separate JSON data

If for some reason you would want to merge different JSON data from different sources then SwiftyJSON still has you covered! It is done by simply using the built-in .merge function:

Notice that any new data is added to an existing array, while any new data with the same key like β€œage” and β€œcity” are updated with the new value!. This is very helpful with comparing and updating old data and new data.

Conclusion

That’s about it for this first look into to SwiftyJSON, with these information you should be equipped enough to utilize it in your swift project, if you ever need extra info you can check out the official guide and documentation here. Good luck and have fun coding! πŸ™‚


Further Reading


Leave a Comment

Share
Tweet
Pin
Share
Buffer