How to use SBJSON and TouchJSON

We at ObjectGraph have mostly used SBJSON, An excellent library from Stig Brautaset which implements a strict JSON parser and generator in Objective-C. Recently we noticed others using TouchJSON and wanted to explore it to see if it offers any advantages over SBJSON.

There has been a good discussion on this subject on which can be read here.

I will show how to use each of these libraries to decode JSON code in this post.

Touch JSON:

Include the following in your header

#import "CJSONDeserializer.h"

NSString *twitterTrendsUrl=@"";
NSData *flickrData=
[NSData dataWithContentsOfURL:[NSURL URLWithString:twitterTrendsUrl]];
NSError *theError = nil;
id theObject =
 [[CJSONDeserializer deserializer] deserialize:flickrData error:&theError];
NSLog(@"Error: %@", theError);
NSLog(@"Result: %@", theObject);	


The thing i like about SBJSON is it adds functions directly into NSString to get NSDictionary or NSArray objects when deserializing JSON strings.

Start with including the following header

#import "JSON.h"

Then you can simply use the following code

NSString *twitterTrendsUrl=@"";
NSString *output=
[NSString stringWithContentsOfURL:[NSURL URLWithString:twitterTrendsUrl]];
id theObject=	[output JSONValue];

Please remember stringWithContentsOfURL has been deprecated so I would not recommend using it. We also just include the entire source of the specific JSON library when building our apps.

By: gavi on: