IPhone, synchronous and asynchronous JSON Parse

A common need in Iphone or mobile applications is to get remote Data using JSON servers. In this post i will speak about the two possibilies : Synchronous and Asynchronous calls and how to deserialise JSON Data with JSON Framework for Objective-C.

So you will need to import the class files of the JSON Framework into your project first.

Synchronous Call

responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];
NSURLResponse *response = nil;
NSError *error = nil;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//json parse
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [responseString JSONValue];
//Accessing JSON content
NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );

Some explanations :

response is the url response for the json call

error is error returned by NSURLConnection

newData is data returned by the server

Notice that you can cast the JSON deserialized data into a NSDictionnary or an NSMutuableArray.

ASynchronous Call

To make an Asynchronous call we’ll need to use NSURLConnection with initWithRequest method, then we need to implement differents other methods to handle the finish of data loading, error handling etc.

//in the viewDidLoad
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];//asynchronous call
[[NSURLConnection alloc] initWithRequest:request delegate:self];

Implementing delegate methods :

- (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 {
    NSLog(@"%@", error);
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];
    NSDictionary *jsonObject = [responseString JSONValue];
    NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );
    [connection release];