Consuming Webservices & Parsing JSON Response Tutorial :Part 2

Hi Folks,

This is the Part 2 of  Consuming Webservices & Parsing JSON Response Tutorial

Previously we have consumed webService using NSURLConnection and got the response successfully .

Now time to parse the JSON response and populate data on UITableView.So the question is Is There any external library to parse raw JSON string?

Yes, there is numbers of external JSON framework which makes developers job easy.For this tutorial we are going to use SBJson framework

You can grab this framework from here and if you have not read part 1 just go through it here

How to install JSON framework?

The simplest way to start using JSON in your application is to copy all the source files (the contents of the Classes folder) into your own Xcode project.

  1. In the Finder, navigate into the Classes folder.
  2. Select all the files and drag-and-drop them into your Xcode project.
  3. Tick the Copy items into destination group’s folder option.
  4. Use #import “SBJson.h” in your source files.

Parsing Raw JSON

The first thing you should do, if you do not understand exactly what’s going on, is to NSLog thedescription of the JSON parser output. This will be a “list” of NSDictionary and NSArray, and when you see the description output you will understand that there is a one-to-one mapping of JSON “object” to NSDictionary

I have created one method where my parsing logic goes

declare it in .h file

-(NSMutableArray *)parseJsonResponse:(NSString *)rawJsonResponse;

in .m file implement this method as

-(NSMutableArray *)parseJsonResponse:(NSString *)rawJsonResponse

{

NSArray *responseKeyValueArray;

NSError *error;

SBJSON *json = [[SBJSON new] autorelease];

NSDictionary *responseKeyValueDict = [json objectWithString:rawJsonResponse error:&error];

#if DEBUG

NSLog(@”JSON parsing responseKeyValueDict: %@”, responseKeyValueDict);

#endif

if (responseKeyValueDict == nil)


{

#if DEBUG

NSLog(@”JSON parsing failed: %@”, [error localizedDescription]);

#endif

}

else {

if([responseKeyValueDict  valueForKey:@”list”] )

{

responseKeyValueArray  =[responseKeyValueDict  valueForKey:@”list”];

#if DEBUG

NSLog(@”responseKeyValueArray ::%@”,responseKeyValueArray);

#endif

if ([responseKeyValueArray isKindOfClass:[NSArray class]])

{

NSMutableArray *artistdetails = [[NSMutableArray alloc]init];

for(int i=0;i<[responseKeyValueArray count];i++)

{

NSDictionary *keyValueIndex = [responseKeyValueArray objectAtIndex:i];

#if DEBUG

NSLog(@”keyValueIndex::%@”,keyValueIndex);

#endif

Artist *artist=[[Artist alloc]init];

artist.imageName=[keyValueIndex objectForKey:@”image”];

artist.artistName=[keyValueIndex objectForKey:@”name”];

#if DEBUG

NSLog(@”artist.artistName::%@”,artist.artistName);

#endif

[artistdetails addObject:artist];

[artist release];

}

#if DEBUG

NSLog(@”artistdetails %d”,[artistdetails count]);

#endif

return [artistdetails autorelease];

}

else

{

return nil;

}

}

}

return  nil;

}

Call this method in connectionDidFinishLoading .modify it as

– (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

// do something with the data

// receivedData is declared as a method instance elsewhere

NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

NSString *responseString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];

NSLog(@”Succeeded! Received JSON String %@ “,responseString);

// parse raw json response

parsedResponseData=[self parsedJsonResponse:responseString];

// release the connection, and the data object

[connection release];

[receivedData release];

}

Now we have Artist information, populate data over UITableView.To achieve this reload tableview and modify you cell for row method as below.

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

{

static NSString *CellIdentifier = @”ArtistCell”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

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

}

if([parsedResponseData count]!=0)

{

// Configure the cell.

Artist *a = [parsedResponseData objectAtIndex:indexPath.row];

NSLog(@”artist name isin cellfor index path %@”,a.artistName);

NSLog(@”artist image link is %@”,a.imageName);

cell.imageView.image=[self displayImage:a.imageName];

cell.textLabel.text=a.artistName;

}

else

{

if(indexPath.row==0)

{

cell.textLabel.text=@”No Data”;

}

}

return cell;

}

 

To display images to UIImage of table view cell add and implement one more method

-(UIImage*)displayImage:(NSString *)imageUrl

{

NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageUrl]];

UIImage* image = [[UIImage alloc] initWithData:imageData];

return image;

}

Done 🙂

Note:Although you might expect some UI Freeze while scrolling as there is no Lazy Loding of image.To resolve this just keep it your uitableview scroll disable.

Hit run and  output looks like this

 

Artist List

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s