UPDATE:  An Update has been done to JSON Library. It is better you follow this link.

JSON is a lightweight data-interchange format, which is easy for us to read and write. And sadly iPhone has no framework to process and form valid JSON data. But a third party JSON framework is available, which I found to be very useful. It is comes under  BSD license. If you are new to JSON, you have made the right decision to use it and use this link to learn about JSON. What you should do to include  JSON support in your iPhone Application?

WAY 1:

  1. Download the latest JSON framework from the link I have provided.
  2. open the .dmg file and you will get a lot of folders and files. Copy the the SDKs/JSON folder and drop it in to the /Users/USERNAME/SDKs/ .
  3. In your Project, select your target in the left-hand menu and click the blue Info button (Apple-i) and select the “Build” tab.
  4. Make sure “All Configurations” is selected in the “Configuration” drop-down.
  5. Add the following new line to the “Additional SDKs” option:     $HOME/Library/SDKs/JSON/${PLATFORM_NAME}.sdk
  6. Add the following two options to the “Other Linker Flags” option: -ObjC -ljson
  7. Use ‘#import ‘ in your source files. And thats done.

WAY 2:

There is  another obvious way to achieve this. (regardless of the target- iPhone or Mac).

It is including the JSON folder directly in to your project. In this case we need to use

#import “JSON.h” in  the source files

EXAMPLE:

A simple way of converting a NSString object (result from web service) to JSON object is shown below:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

NSData *postData = [url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

[request setURL:[NSURL URLWithString:kURL]];

[request setHTTPMethod:@"POST"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

[request setHTTPBody:postData];

NSURLResponse *urlResponse;

NSError *error;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

[request release];

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
SBJSON *jsonParser = [SBJSON new];

returnValue= (NSDictionary*)[jsonParser objectWithString:jsonString];

[jsonParser release];

[jsonString release];


And thats all for this post….Bye

Advertisements