In the first part of the series, we create an app that parse the JSON from web service without any open source library.

In this second article , we will cover how to Generate JSON data and how to integrate objects and JSON.

We are going to start by changing some UI design.

We have created this view in our first part. now we will do some modifications in that.

We will remove this white BIG textview.

now your view look like below :

Follow below Steps :

  1. Now drag One UILabel , One UIButton and two UITextView.
  2. Delete the sample texts from textview.
  3. Now set the first UILabel text to “Custom Text display :”
  4. Now set the UIButton text to “Generate Json :”

Now your view will look like this :

Now Modify your ViewController.h file

@interface ViewController : UIViewController
{
}
@property (strong,nonatomic) IBOutlet UILabel *lbl_header;
@property (strong,nonatomic) IBOutlet UITextField *txt_webservice_url;
@property (strong,nonatomic) IBOutlet UIButton *btn_Parse_webservice;

// Remove Previous outlet.
@property (strong,nonatomic) IBOutlet UITextView *txt_webservice_response;

// Create outlet for new two TextView.
@property (strong,nonatomic) IBOutlet UITextView *txt_Custom_display , *txt_genertated_json;

 // Create outlet for btn_genertae_json.
@property (strong,nonatomic) IBOutlet UIButton *btn_genertae_json;
 -(IBAction)btn_parse_webserivce_click:(id)sender;

 // Create Method for genertae_json.
-(IBAction)btn_generate_json:(id)sender;
 @end 

Here we create Outlet for both UITextView and UIButton. and create new method named “btn_genertae_json”.

Next :

Go to ViewController.xib

File’s Owner -> Utilities -> Connections inspector. it look like below :

Finally your  Connection inspector look like this :

Go to ViewController.m File

First @synthesize added properties.

@synthesize txt_Custom_display,txt_genertated_json;

Now we Modify -(IBAction)btn_parse_webserivce_click:(id)sender Method

-(IBAction)btn_parse_webserivce_click:(id)sender
{

// Take Webservice URL in string.
NSString *Webservice_url = self.txt_webservice_url.text;
NSLog(@"URL %@",Webservice_url);

// Create NSURL from string.
NSURL *Final_Url = [NSURL URLWithString:Webservice_url];

// Get NSData from Final_Url
NSData* data = [NSData dataWithContentsOfURL:
Final_Url];

// parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
NSArray* Response_array = [json objectForKey:@"loans"];
NSLog(@"Array: %@", Response_array);

// Set Response_array  to textview.
self.txt_webservice_response.text = [NSString stringWithFormat:@"%@",Response_array];

// 1) Get the latest loan
NSDictionary *dict_loan = [Response_array objectAtIndex:0];
NSLog(@"%@",dict_loan);

// 2) Get the latest loan's location information
NSDictionary *dic_location = [dict_loan valueForKey:@"location"];

// 3) Get the Name inforamtion from latest loan.
NSString *str_name = [dict_loan valueForKey:@"name"];

// 4) Disply all information in txt_Custom_display.
txt_Custom_display.text = [NSString stringWithFormat:@"Loan : %@ Place name : %@ town Name : %@",str_name,[dic_location valueForKey:@"country"],[dic_location valueForKey:@"town"]];
}

In above code. i have just fetch some particular value from JSON response. and show them in textview. Like this way you can access and use JSON response.

Generating JSON Data

 

Now we will build Some JSON data from NSDictionary. which will be able to send server.

 

Now we implement -(IBAction)btn_generate_json:(id)sender Method

-(IBAction)btn_generate_json:(id)sender
{
// Here we create a demo dictionary from which we generate json.
NSDictionary *Demo_dic = [NSDictionary dictionaryWithObjectsAndKeys:@"Ramesh",@"Name",@"Sharma",@"Surname",@"28/6/1991",@"BirthDate", nil];

// Here we convert Object to data
NSError* error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:Demo_dic
options:NSJSONWritingPrettyPrinted error:&error];

// Display out the data contents
txt_genertated_json.text = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
} 

In above code :

Here we build an NSDictionary called “Demo_dic” where we store the some information as Name, Surname, and BirthDate in different keys and values.

Then we use dataWithJSONObject:options:error: – the opposite to the JSON API we just used earlier. It takes in an object and turns it into JSON data.

 

For the options parameter We used this – NSJSONWritingPrettyPrinted.

If you want to send the JSON over the Internet to a server use kNilOptions as this will generate compact JSON code,

and if you want to see the JSON in nice format then use NSJSONWritingPrettyPrinted as this will format it nicely.

And at last we do initializing an NSString with initWithData:encoding: and we easily get the text representation of our JSON data and we show it in txt_generated_json textview.

Now save and run your program.

It will look like this.

Integrating Objects and JSON

 

In this section we extend foundation class (For Ex : NSMutableDictionary) with our own methods which help us to covert TO and FROM JSON data.

Here we implement example for NSDictionary. and also see how can we use this methods.

Go to ViewController.m file

And Paste the below code just above: @implementation ViewController

// We create category for NSMutableDictionary Class

@interface NSMutableDictionary(JSONCategories)

// Method which convert data into Objects

+(NSMutableDictionary *)MutabledictionaryWithContentsOfURLString:
(NSString*)urlAddress;

// Method which convert Objects into data
-(NSData*)toJSONdata;
@end

// Implementation Part

@implementation NSMutableDictionary (JSONCategories)

// Method Implementation which convert data into Objects

+(NSMutableDictionary *)MutabledictionaryWithContentsOfURLString:
(NSString*)urlAddress
{
NSData* Response_data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: urlAddress] ];
NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:Response_data
options:NSJSONReadingMutableContainers error:&error];
if (error != nil) return nil;
return result;
}

// Method Implementation which convert Objects into data

-(NSData*)toJSONdata
{
NSError* error = nil;
id result_data = [NSJSONSerialization dataWithJSONObject:self
options:kNilOptions error:&error];
if (error != nil) return nil;
return result_data;
}
@end 
So sort description of above code is as following : We create TWO methods.
1. +(NSMutableDictionary *)MutabledictionaryWithContentsOfURLString: (NSString*)urlAddress  :-

Which get NSString from web-address , which Handle all parsing / downloading and at last it will return an instance of NSMutableDictionary.

Here is the examples how you can use this method

NSMutableDictionary* myInfo =

[NSMutableDictionary MutabledictionaryWithContentsOfURLString:

@”https://api.kivaws.org/v1/loans/search.json?status=fundraising”];

2. -(NSData*)toJSONdata :-

You can call this method by an instance of NSDictionary , which will return JSON data.

Here is the examples how you can use this method

NSMutableDictionary *Demo_dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@”Ramesh”,@”Name”,@”Sharma”,@”Surname”,@”28/6/1991″,@”BirthDate”, nil];

NSData* json = [Demo_dic1 toJSONdata];

Its Done.

Here is example_project with all the codes from above tutorial.