Hi this is Marin - the author of Touch Code Magazine, I hope you are enjoying my tutorials and articles. Also if you need a bright iPhone developer overseas contact me - I do contract work. Here's my LinkedIn profile
You can clone this project from GitHub!
This post features open source code, which you can find on GitHub.
After you done with the tutorial don't forget to check out the repo at https://github.com/icanzilb/Fetch-and-parse-JSON
This tutorial is outdated
Good news though, I already prepared a newer version!
This tutorial is outdated as it does not use data models to work with JSON. When I was writing the post I thought for a Hello World models are not needed, but now I believe one should learn properly from the start. Please read my newer JSON tutorial.
Or for some reason read the old one:
» Close this helpful message
Tutorial: Fetch and parse JSON in iOS6

One of the more popular articles on Touch Code Magazine is the “Tutorial: Fetch and parse JSON“. However I wrote this tutorial quite some time ago, so now I decided to re-write it so that it uses modern technologies like ARC, Stroryboards, NSJSONSerialization, etc.

When you have finished this tutorial, you will know how to:

  • Asynchronously load a remote JSON feed from Internet
  • Easily handle invalid JSON data
  • Convert JSON into Objective-C objects
  • Use the JSON data in your UI

Let’s start!

Prepare the Xcode project and UI

Create a new Xcode project (using XCode 4.5 or newer) and select the Single View iOS project template. Make sure “Use Automatic Reference Counting” is checked.

From the project file list on the left side select MainStoryboard.storyboard. Drop in a UILabel and resize it to take most of the screen, like so:

While the label is selected, open up the properties inspector on the right and for the “Lines” property enter “0”. That will make the text you fill in the label wrap onto multiple lines.

Now open up ViewController.m and replace the empty @interface declaration of the top of the file with:

Now open up back MainStoryboard.storyboard and connect the outlet you just declared. Hold the “ctrl” key on your keyboard and drag with the mouse as on the schema below. Choose label from the menu that pops up when you release the mouse button:

OK, now your label is connected to your ViewController class, so you can go on with writing the Objective-C for your project.

Fetching JSON feed from Kiva.org

As in the original JSON tutorial on Touch Code Magazine in this tutorial you are going to fetch a JSON feed from Kiva.org – an organization that provides micro-funding to entrepreneurs in the 3rd world countries.

The JSON feed with the latest loans that need funding you can find at: http://api.kivaws.org/v1/loans/search.json?status=fundraising. You are going to load that feed and show human readable information about the latest loan.

The structure of the JSON feed you can examine on the screenshot below (taken in Charles – the single most valuable tool if you’re working on an app, which communicates via JSON, XML, or something similar)

So the JSON response’s top object is a dictionary, which has two keys “paging”(1) and “loans”(2). You will use the “loans” array – it contains a list of loan objects (3), and you can see the structure of a single loan object (4) – it has keys like name, country, use, sector, loan_amount, etc.

Working in the background

To do the heavy work network communication without blocking your app’s UI, you’ll need to execute the networking code in the background. Open up ViewController.m and at the end of the viewDidLoad method add:

I’ll go step by step to explain the code above:

  1. First you use dispatch_async to execute a block of code asynchronously in the background
  2. Inside the block you fetch the contents of the Kiva JSON API URL – you just create a new NSData object by calling dataWithContentsOfURL:
  3. Next you call NSJSONSerialization to convert the piece of data into objects (you don’t provide an error parameter – you’ll do error handling in a bit)
  4. Then you need to update the UI with the new data, therefore you need switch to execution on the main tread- another dispatch_async switches to the main thread
  5. Finally, on the main thread you call updateUIWithDictionary: method of the ViewController class (you will implement it in a second)

Did you notice that you actually already fetched and parsed the JSON feed? Yes, since iOS5 it’s actually that easy to grab data from a web server :)

But wait – in a second you will use the new iOS6 features to dig through the result with just few keystrokes!

Updating the app UI

Now let’s implement the updateUIWithDictionary: method. It takes one parameter in – you expect an NSDictionary, but it might be also nil if JSON feed is corrupt or unreachable. Paste in this new method:

The code is just one line – you create a new string with some placeholders, and you fill in the placeholders with text from the fetched loan data object. You wrap this operation in a try block – this way if the fetched data object doesn’t have the structure you expect, the program will fall into the catch block and you can do some error handling there (you add the catch block in a second).

Note how easy it is in iOS6 to drill through nested data objects. For example:

Gets the “loans” key in the “json” dictionary, then casts it to an array and gets the very first element. This first element is than casted to a dictionary and you get the “location” key out of it and the value of this key is casted to a dictionary and you fetch the object of the “country” key.

Isn’t it actually easier to understand what’s going on when you see the code, than to have it spelled out in plain English :) ?

So by executing this line you set the text of the label to something like the one in the screenshot:

However you are not done just yet. At the end of the updateUIWithDictionary method you need to also handle errors, add this code after the closing bracket of the catch block:

If there was any exception thrown while you were digging through the data you just show an alert to the user and dump the exception description in the console – that should suffice for our demo project!

And … that’s it! You know now how to fetch data from a remote server, parse incoming JSON and use it in your app.

Wrap up

Hopefully this tutorial helped you and I’ll be glad to hear from you in the comment section below.

Cheers, Marin

The post was originally published on the following URL: http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/




You can clone this project from GitHub!
This post features open source code, which you can find on GitHub.
After you done with the tutorial don't forget to check out the repo at https://github.com/icanzilb/Fetch-and-parse-JSON

Marin Todorov

is an independent iOS developer and publisher. He's got more than 18 years of experience in a dozen of languages and platforms. This is his writing project.
» Contact    » Add Marin on Google+

  1. horseshoe7 on Wednesday 26, 2012

    I didn’t think the use of @try and @catch with exceptions was encouraged in iOS development. I rarely see it in any other source code and I’m wondering if this is best practices.

  2. Marin on Wednesday 26, 2012

    Yes, it is not encouraged :) But I’m a big boy so I can decide for myself :)

  3. Stan on Wednesday 26, 2012

    Hi, nice article, thanks.

    For setting up the label (i.e. IBOutlet UILabel *label), you are not using “built in” Xcode feature via Assistant editor by dragging the label right into the ViewController.h and ending up with the following declaration: @property (weak, nonatomic) IBOutlet UILabel *label.

    What is the better usage: yours and/or the one from Xcode ?


  4. Marin on Wednesday 26, 2012

    Hey Stan, they are both valid and I don’t think there’s any difference in the produced code anyway. You can just use whichever you find better for your workflow :) Marin

  5. Rodrigo on Wednesday 26, 2012

    Hi Marin! This article is awesome! Really, I was really waiting for a json parsing tutorial of iOS 6. Just one question, so If we wanted instead of pasting the parse in a label, to go to a UITableView, how does this change the code given? Thanks!

  6. Marin on Wednesday 26, 2012

    Hi Rodrigo, I’m glad you like the tutorial. Just use normal table view code, but when it comes to filling in text in the table cells, use the indexPath provided to access the proper index in the fetched loans – json[@"loans"], like json[@"loans"][indexPath.row] and then fetch the details you want to use. Marin

  7. Rodrigo on Wednesday 26, 2012

    Thanks for your quick response! I’ll try it now, I’m looking forward to next tutorials, very interested in themes like sorting the NSDictionary for TableView and stuff like that.

    Really awesome your job!

  8. beginner on Wednesday 26, 2012

    hey martin, thanks for the nice article!

    I still have some problems and can not finish your tutorial :/

    could you upload your program? i’m really interest in JSON and it will help me very much!


  9. Rich on Wednesday 26, 2012

    This looks like exactly what I’ve been looking for, but I’m getting a compile error at the line [self updateUIWithDictionary: json]; saying
    No visible @interface for ‘ViewController’ declares the selector ‘updateUIWithDictionary.’

    Is there a framework file I need to add to my project for dealing with JSON arrays?

  10. Marin on Wednesday 26, 2012

    Hi Rich, check if you have the latest version of Xcode. Older versions of Xcode needed explicit method declarations in the interface, while 4.5 doesn’t – that might be as well the problem.

  11. Rich on Wednesday 26, 2012

    Thanks for the quick response. I’m actually using the latest and greatest 4.5.

  12. Rich on Wednesday 26, 2012

    Never mind. I figured it out.

  13. Lakmali on Wednesday 26, 2012

    Hi Marin,
    when I run the app I’m getting (null) for all the values. Is there something else you have not mentioned in the tutorial that I have missed. A setting or something

  14. Lakmali on Wednesday 26, 2012

    Sorry this was blocked by the proxy. Very useful and easy tutorial.

  15. balan on Wednesday 26, 2012

    Nice tutorial…Expecting more tutorials like this way….Thanks a lot…

  16. duffman on Wednesday 26, 2012

    This was exactly what I’ve been looking for!! Just wondering how you would set up a refresh button? The MySQL database that is being converted to JSON is constantly updated, and users need to refresh…not sure what to type in the IBAction though…Cheers!

  17. charan on Wednesday 26, 2012

    Let’s say I have a large # of records, what is the best place to update the data? inside main queue?

  18. Marin on Wednesday 26, 2012

    especially if you have lots of data the best way is to work in the background … if possible call only reloadData on the main queue

  19. Rakesh on Wednesday 26, 2012

    Hi tried out the above code and got the folloeing error “Invalid value around character 0. What might be the prob??

  20. Marin on Wednesday 26, 2012

    I never had an error like that, but it sounds like a broken JSON feed

  21. twitter_hugocarlmartin on Wednesday 26, 2012

    Hi Marin, awesome tutorial.

    I’m using your code quiet successfully. I put the code in viewDidAppear because it gives me the opportunity to toggle between tabs and the correct elements in the json. Hope you understand. In the log everything looks perfekt but I cant get it in my tblview. I tried to to put it in cellForRowAtIndexPath like I usually do, but no luck. Any ideas?

    Thanks for good tutorial.

  22. Marin on Wednesday 26, 2012

    do you call reloadData on your table after you fetch the JSON?

  23. hugocarlmartin on Wednesday 26, 2012

    Yes I did, I tried it on different places.

  24. hugocarlmartin on Wednesday 26, 2012

    Problem solved, thx.

  25. [...] been following this tutorial. I was trying to apply it to my case. The JSON feed I’ll be using is: JSON [...]

  26. [...] Hi this is Marin – the author of Touch Code Magazine, I hope you are enjoying my tutorials and articles. Also if you need a bright iPhone developer overseas contact me – I do contract work. Here's my LinkedIn profile NOTE: I have posted a newer version of this same tutorial, which makes use of technologies available in iOS5 and iOS6.If you want a more flexible and modern code have a look at the more recent version, which you can find here: http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/ [...]