Retrieving JSON Data In iPhone Apps

As described at www.json.org, JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. The JSON format is one of two things; a list of name/value pairs that can be realized as an object, record, struct, dictionary, hash table, keyed list, or associative array or an ordered list of values which in most languages is realized as an array, vector, list, or sequence.

JSON logo

JSON logo

The JSON format is often used as an alternative to XML to transmit structured data over a network, its biggest use being in Ajax web application programming.

Below are instructions for how to retrieve and parse JSON formatted data in an iPhone app.

Adding JSON Framework To Your XCode Project

To use JSON in an iPhone app you first need to download the JSON Framework for Objective-C from its Google Code page.

When it is downloaded, mount the DMG.

Finally, drag and drop the JSON directory onto the Classes folder icon in the Groups & Files panel in XCode.

Retrieving JSON Data

First of all make sure that you include the JSON.h file in your implementaion(your .m file):

#import "JSON.h"

To retrieve JSON data use an NSURLConnection to issue an HTTP request. To do this you will need an NSMutableData variable to hold the response data. Create it in the interface (.h file) with:

NSMutableData *responseData;

and

@property (nonatomic, retain) NSMutableData *responseData;

and don’t forget to synthesize in the implementation (.m file):

@synthesize responseData;

Next you need to make an HTTP request with NSURLConnection so start by initializing responseData:

responseData = [[NSMutableData data] retain];

Then make the request:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.someurl.com/somefile.json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

Then you need to include the following methods to process the NSURLConnection and save the JSON data into the responseData variable:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

Making Use Of The JSON Data

To make use of the JSON data use the connectionDidFinishLoading: method. Here is an example with some simple error checking:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];

	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];

	if ([responseString isEqualToString:@"\"Unable to find specified resource.\""]) {
		NSLog(@"Unable to find specified resource.\n");
	} else {
		NSDictionary *dictionary = [responseString JSONValue];
		self.someVariable = [dictionary valueForKey:@"somekey"];
	}
}

In this connectionDidFinishLoading: method you can use any of the key names you know to be in the JSON data to get their values and store them or use them as you need.

Hopefully this helps you to get started using JSON data in your iPhone apps.

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Technorati
  • LinkedIn
  • RSS
  • Slashdot
  • Twitter

About Jason Job

I am a technologist, music producer and an obsessive student of the Internet. I create sound, write code and make things with electronics and microcontrollers. I work as a software developer and consultant and am currently focused primarily on mobile applications for iPhone, iPad and iPod Touch.
This entry was posted in code, iPhone, online. Bookmark the permalink.

2 Responses to Retrieving JSON Data In iPhone Apps

  1. mike says:

    your post is good but it is not explained how I can send a JSON object with the request.

  2. Jason Job says:

    Mike, the request in my example is only to receive JSON data. I haven’t yet needed to send JSON data.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>