In iOS 5 apple introduced a new built –in API for communicating with the JSON.This API is really helpful to work with JSON read and write functionalities. If you are not familiar with JSON (JavaScript Object Notation), it is a lightweight data-interchange format that is often used to send data over a network connection. It is easy for humans to read and write. It is easy for machines to parse and generate.
For example, If you have a array of Data (in String Format), the JSON representation would be:
[ "firstName", "lastName", "age", "place", "email"]
JSON objects are also come along with the pet objects with member variables (key value pair) format, the JSON representation would be:
[
{ "firstName": "John", "lastName": "Smith", "age": "27","place": "America", "email": "john_smith@gmail.com" }
]
It’s So simple and You can learn more about the
JSON from here.
Why JSON is Important?
Nowadays, most of the powerful third party’s such as Google, Yahoo provides JSON API to interchange data with the server and client. When you make a web service call with a query string, it will return JSON formatted data. When you write your own web services, it is easy to convert your data into JSON format, and also the learning part of JSON is quite simple. Most attractive part of JSON based web service is Intrinsic Simplicity.
In this tutorial, we will learn about how we can work with JSON in IOS 5.0 and above.
Working with JSON in IOS 5 and above:-
In the previous versions of IOS (below version 5), to parse the JSON data we are using a third party library know usSBJson. It is a bit heavy process and we need to include all the files to our project, and also the data manipulation process is also bit hard.
So finally apple added a JSON Parser in to the Cocoa library. From my personal experience, I played many times with JSON in many projects, so I feel very comfortable like the way the apple did in iOS 5.With the help of this library we can easily turn objects like NSString, NSNumber, NSArray and NSDictionary into JSON data and vice versa, no need to include external libraries – everything is done natively and super fast.
Overview:-
Top level object must be NSArray or NSDictionary .
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
All Numbers are not NaN or infinity.
Class Methods:-
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error
+ (BOOL)isValidJSONObject:(id)obj
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
+(id)JSONObjectWithStream:(NSInputStream*)stream options:(NSJSONReadingOptions)opt error:(NSError **)error
+(NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream*)stream options:(NSJSONWritingOptions)opt error:(NSError **)error
In this tutorial, we are going to get hands-on experience in the new native JSON support. Step by step we are going to build a sample application which helps us to understand the working of JSON native Support.
Getting Started:-
Open Xcode from the developer tools, Click on the Create new project and select the single view based application. Enter the Product name as JSON,enter the Company identifier name and change the device family to iPhone,click Next and save the project by clicking Create.Start up screen will look like below.

Next we need to add a text file to the project,for that we need to right click on the project click on the other category and click on the empty file template. Now we need to rename the empty file as jsonText.txt . Next we need to add the
JSON data to the jsonText.txt. The JSON data representation will be look like this:
{"AppBgColor": "eeeeee","AppName": "JSON Demo","AppVersion": "1.0","developerName": "safil", "contact": "safilsunny@gmail.com"}
Now we need to add some UI elements to the ViewController.xib and add corresponding IBOutlet in the ViewController.h file, and wire the IBOutlet to the xib
@interface ViewController : UIViewController
{
IBOutlet UILabel *AppBgColorLabel;
IBOutlet UILabel *AppNameLabel;
IBOutlet UILabel *AppVersionLabel;
IBOutlet UILabel *developerNameLabel;
IBOutlet UILabel *contactLabel;
}
Now we need to create a method to read the local jsonText.txt data and parse the JSON to the Foundation objects. Open the ViewController.m and create a function to interact with the parse JSON text button in the UI. The below code snippet will indicate the implementation of JSON Parser .
//interacting with the parse JSON Button with the UI
-(IBAction)parseLocalJSON:(id)sender{
//Getting the file path from the local bundle.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"jsonText" ofType:@"txt"];
//Convert the content of file to NSData
NSData* data = [NSData dataWithContentsOfFile:filePath];
//fetch the data to the JSON Foundation opject.
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
}
the above function will interact with the UI button named parse JSON Text, when ou touch up inside the button, it will call the parseLocalJSON function and convert the jsonText file data to the NSData. Next code snippet will explain about the conversion model of NSData to the NSDictionary.
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//process the JSON Foundation object to the view.
[self processData:json];
}
At the end of the fetchedData function it will call the processData function with the JSON object dictionary as parameter. This function will separate according to the key-value process.
-(void)processData:(NSDictionary *) JSONObject{
NSString *AppBgColor = [JSONObject valueForKey:@"AppBgColor"];
NSString *AppName = [JSONObject valueForKey:@"AppName"];
NSString *AppVersion = [JSONObject valueForKey:@"AppVersion"];
NSString *developerName =[JSONObject valueForKey:@"developerName"];
NSString *contact =[JSONObject valueForKey:@"contact"];
NSLog(@"AppBgColor: %@", AppBgColor);
NSLog(@"AppName: %@", AppName);
NSLog(@"AppVersion: %@",AppVersion);
NSLog(@"developerName: %@",developerName);
NSLog(@"contact: %@",contact);
AppBgColorLabel.text =AppBgColor;
AppNameLabel.text =AppName;
AppVersionLabel.text = AppVersion;
developerNameLabel.text=developerName;
contactLabel.text=contact;
self.view.backgroundColor =[UIColor greenColor];
}
OK! Let’s have a look – hit Run and see what comes up:
Now touch up inside the Parse JSON text button, it will change the UI according to the
JSON Value.

instead of parsing the local JSON text file we can use the data from the live server,for that we need to specify the url path like this
NSURL *url =[NSURL URLWithString:@"http://safilsunny.com/webservice"];
NSData* data = [NSData dataWithContentsOfURL:url];
Just replace this code snippet with the above code.
//Getting the file path from the local bundle.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"jsonText" ofType:@"txt"];
//Convert the content of file to NSData
NSData* data = [NSData dataWithContentsOfFile:filePath];
You are done. You can download the source code from here. happy coding…