Parsing JSON data

JSON (JavaScript Object Notation) is a lightweight format, which is widely used to send data over the internet. The JSON format includes dictionaries and arrays. In this tutorial we will parse some weather data and display it on the screen. We are going to make use of the Dark Sky API that's been used for the stunning weather app Dark Sky. To use the API we need to register to obtain the API key. Go to the developer portal, register for the key and save the string. Further along in this tutorial you must paste this string into our code.

Update: Oct 01, 2014. The rewritten tutorial in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use JSONDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards and Use Automatic Reference Counting checkboxes are selected (Unit Tests will not be necessary for this project).

If you take a look in the docs of the Dark Sky API you see you can make a forecast request with the following format,LON

For the Latitude and Longtitude we going to use New York in this example. For New York these are the values:

LAT = 42.7243 and LON = -73.6927

So the url becomes,-73.6927. Paste in your API key and you will see some output, which will problaby be different than the following output. At the bottom you will see the following data

currentTemp: 45, timezone: "America/New_York (EDT, -0400)", currentSummary: "clear", hourSummary: "clear", daySummary: "clear", isPrecipitating: false, currentIntensity: 0, minutesUntilChange: 0, checkTimeout: 7200

As you can see this are all key-value pairs. For this tutorial we are going to use the values of currentTemp, timezone and hourSummary.

First we build the User  Interface, go to the ViewController.xib and drag and rename the following labels to the view.

Go to ViewController.m and create the following properties in the @interface section.

@property (nonatomic, weak) IBOutlet UILabel *timeZone;
@property (nonatomic, weak) IBOutlet UILabel *hourlyForecast;
@property (nonatomic, weak) IBOutlet UILabel *currentTemp;

Go back to ViewController.xib and make the following connections (to the unnamed labels)

  • top Label -> timeZone
  • middle Label -> hourlyForecast
  • bottom Label -> currentTemp

At the top of viewController.m we define some constants to create the URL of the request to the Dark Sky API. This way it is easier to change some of the values if we want.

#define DarkSkyURL @"" #define API @"your_API" 
#define LAT @"/42.7243"
#define LON @",-73.6927"

#define fullURL (DarkSkyURL API LAT LON)

Of course you must paste in your own API in the API constant. In ViewDidLoad Add the following lines

dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{ NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:fullURL]]; [self performSelectorOnMainThread:@selector(fetchedForecast:) withObject:data waitUntilDone:YES]; });

First we create a queue object to make the request on a different thread so the User Interface will not be blocked during the request. Next we put the url in a data object and called the helper method fetchedForecast. Let's implement this method


- (void)fetchedForecast:(NSData *)responseData 
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

self.timeZone.text = [json objectForKey:@"timezone"];
self.hourlyForecast.text = [json objectForKey:@"hourSummary"];
self.currentTemp.text = [NSString stringWithFormat:@"%@",[json objectForKey:@"currentTemp"]];

With the NSJSONSerialization JSONObjectWithData:options:error method the actual parsing is performed. The parsed data will be written into a dictionary, which we can use to set the text property of our labels. Note we have to transform the integer value of currentTemp into a string.

Build and Run, you will see the current forecast values of New York

You can download the source code of the JSONDemo at the ioscreator repository on github.