JSON in iPhone

Introduction

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format. It is easy for humans to read and write. JSON is a data format that is completely language independent. It is a collection of name/value pairs and an ordered list of values.

In this article I will create a Single view application and I will use a table view from outlet to connect it's delegate or datasource to the file owner. Here I use an API loan service and fetch a "name" entity and show it in the table.

To understand it we use the following.

Step 1

Open XCode by double-clicking on it. 

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now Select Single View Application and click on Next. 

Step 4

Now provide your Product Name.

Step 5

Select the location where you want to save your project and click on Create. 

Step 6

Now we write the code.

ViewController.h

//

// CirclesViewController.h

// jsonTest

//

// Created by Sachin Bhardwaj on 12/12/12.

// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface CirclesViewController : UIViewController{

NSMutableArray *m_userprofiledatarray;

NSURL *_feedurl;

NSMutableData *responseData;

NSHTTPURLResponse* httpResponse ;

NSString *responseString;

int responseCode;

NSMutableArray * name;

NSMutableArray * activity;

IBOutlet UITableView *table;

}

@property(strong,nonatomic)IBOutlet UITableView *table;

@property (nonatomic, assign) BOOL islistDisplay;

@property(nonatomic,copy) NSMutableArray * name;

@property(nonatomic,copy) NSMutableArray * activity;

@end


ViewController.m

//

// CirclesViewController.m

// jsonTest

//

// Created by Sachin Bhardwaj on 12/12/12.

// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//

#import "CirclesViewController.h"

@interface CirclesViewController ()

@end

@implementation CirclesViewController

@synthesize name,activity;

@synthesize table;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

- (void)viewDidLoad

{

[super viewDidLoad];

// CircleGroupName = [[NSMutableArray alloc]init];

//

// [self getdata];

}


-(void)viewWillAppear:(BOOL)animated{

name = [[NSMutableArray alloc]init];

[super viewWillAppear:animated];

[self getdata];

}

-(void)getdata{

NSString *urlstring = [NSString stringWithFormat:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];

_feedurl = [NSURL URLWithString:urlstring];

NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:_feedurl];

//do post request for parameter passing

[theRequest setHTTPMethod:@"GET"];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( theConnection )

{

[theConnection release];

}

else

{

[theConnection release];

}

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

responseData = [[NSMutableData alloc] init];

httpResponse = (NSHTTPURLResponse*)response;

responseCode = [httpResponse statusCode];

responseString = [NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *)response statusCode]];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data11{

[responseData appendData:data11];

NSString* myString;

myString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

[myString release];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

if(responseCode == 200){

NSString *_responsedatastring = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding]autorelease];

NSData* logindata = [_responsedatastring dataUsingEncoding:NSUTF8StringEncoding];

NSArray *profileFeeds_array = [NSJSONSerialization JSONObjectWithData:logindata options: NSJSONReadingMutableLeaves error:nil];

self.name = [profileFeeds_array valueForKey:@"loans"];

self.activity = [name valueForKey:@"name"];

NSLog(@"activity:%@",activity);

[table reloadData];

}else{

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please try again.Network Problem"

message:nil

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

alert.tag = 2;

[alert show];

[alert release];

}

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

return YES;

}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

// [pullTableView reloadData];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [name count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell==nil)

{

cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}

cell.textLabel.text = [activity objectAtIndex:indexPath.row];

return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

// Navigation logic may go here. Create and push another view controller.

}

@end

Step 7

Now we check the output in a console window.

Consol-window-output.png

It is a running API so sometimes the output will be different. But here my main purpose is to explain how to use a JSON service in iPhone.

Step 8

Finally we click on the Run button to show the output.

Output 1 in iPhone:

Output1-in-iPhone.png

Before scrolling down to show output in the table.

Output 2 in iPhone:

Output2-in-iPhone.png

After scrolling down to show output in the table.


Summary 

API Reference-http://build.kiva.org/api

http://api.kivaws.org/v1/loans/search.json?status=fundraising

Up Next
    Ebook Download
    View all
    Learn
    View all