Tuesday, August 18, 2009

Cocoa with JSON data using SBJSon

Hi all,

This is my very first blog. For this blog, I would like to thank to Stig Brautaset for bringing out an excellent JSON Parser " SBJSON".
Firstly download SBJSON framework from

There are two ways to include SBJSON framework into the code.

1) Either include this framework into the framework folder of the application

2) Or Copy all the classes into 1 folder in Classes folder.

Here are the list of the classes available in SBJSON framework


"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

"SBJsonParser.h"

"SBJsonWriter.h"

"SBJsonBase.h"


And in all these

------

"SBJSON.h"

"NSObject+SBJSON.h"

"NSString+SBJSON.h"

------


the above 3 classes are only imported in JSON.h file


And now import JSON.h file into the class, where we are going to communicate through the HTTP JSON response into Cocoa.



Now I am going to share the way to interact with the server for GET request


1)

- (NSMutableArray *) downloadGetData:(NSString *)urlString

{

id response = [self objectWithGetUrl:[NSURL URLWithString:[NSString stringWithFormat:@"%@" ,urlString]]];

NSMutableArray *record = (NSMutableArray *)response;

return record;

}


Here we are taking the URL in string where we want to hit, to get the response, will call the method objectWithGetUrl:(NSURL*)type to get the response of the type id assigning it the value into NSURL format by converting the string into NSURL.




2)

- (id) objectWithGetUrl:(NSURL *)url

{

SBJSON *jsonParser = [SBJSON new];

NSString *jsonString = [self stringWithGetUrl:url];

// Parse the JSON into an Object

id data = [jsonParser objectWithString:jsonString error:NULL];

//Release SBJSon Object

[jsonParser release];

return data;

}


Here, Create a SBJSON object to parse JSON into a native Cocoa object using [SBJSON new]. This object will be in autorelease pool ( it means, it will automatically loose its memory when it will be not in scope).
These we will call the the local method stringWithGetUrl. and the url parameter which we have got in this method will be assign to stringWithGetUrl's parameter.

Then using the JSONParser class

- (NSString *)stringWithGetUrl:(NSURL *)url

{

@try {

NSInteger internetConnectionAvailability = [self internetConnectionAvailable];

if(internetConnectionAvailability == kInternetConnectionAvailable)

{

NSInteger timeInterval = [NSLocalizedString(@"Time Interval", @"Time Interval") intValue];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url

cachePolicy:NSURLRequestReturnCacheDataElseLoad

timeoutInterval:timeInterval];

// Fetch the JSON response

NSData *urlData;

NSURLResponse *response;

NSError *error;

// Make synchronous request

urlData = [NSURLConnection sendSynchronousRequest:urlRequest

returningResponse:&response

error:&error];

if([urlData length] == 0)

{

UIAlertView *alertTest = [[UIAlertView alloc]

initWithTitle:@"Sorry !"

message:@"No Service is available"

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

[alertTest show];

[alertTest autorelease];

return @"";

}

else {

return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

}

// Construct a String around the Data from the response

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}

return @"";

}


Here we have requested the url with Get type request, and getting the result into byte format, and then we will convert it into NSString, the json String, which we are converting to JSON using json parser.


Now here, we will discuss, how could we request the URL with type POST and sending JSON data in request

@try

{

if([self internetConnectionAvailable] == kInternetConnectionAvailable)

{

SBJSON *jsonParser = [SBJSON new];

jsonParser.humanReadable = YES;

NSString *jsonString = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

NSString *changeJSON = [NSString stringWithFormat:@"%@", [refinements JSONFragment], nil];

#ifdef TARGET_IPHONE_SIMULATOR

NSLog(jsonString);

#endif

changeJSON = [NSString stringWithFormat:@"categoryId=%@&refinements=%@",categoryId,changeJSON];

NSData *requestData = [NSData dataWithBytes: [changeJSON UTF8String] length: [changeJSON length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:[NSString stringWithFormat: @"%@results", ServerUrl]]];

NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];

[request setHTTPMethod: @"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody: requestData];

//Data returned by WebService

NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

categorySearchList = (NSMutableDictionary*) [jsonParser objectWithString:returnString error:NULL];

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[jsonParser release];

[request release];

request = nil;

[returnString release];

returnString = nil;

[[GlobalObjects sharedInstance] setCategorySearchList:categorySearchList];

[NSThread detachNewThreadSelector:@selector(saveResultForCategoryinCache) toTarget:self withObject:nil];

}

}

@catch (NSException * e)

{

NSString *msg = [NSString stringWithFormat:@"%@",[e description]];

NSLog(@"hi NSException %@",[e description]);

UIAlertView *errorAlertView = [[[UIAlertView alloc] initWithTitle:@"Exception !" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:nil,nil] autorelease];

[errorAlertView show];

}

@finally

{

}