Thursday, December 20, 2012

Talking to JSON

Isn't it interesting to do so?. And i love the way it is. In the following steps i will explain you the steps reading json file.

my sample json file is here sample.json

     "name" : "A Bend in the river"
     "author" : "V.S. Naipaul"
     "id" : "01"
      "coverurl" :""
     "name" : "Baburnama"
     "author" : "Babur"
     "id" : "02"
     "name" : "The secret"
     "author" : "Acharya Rajneesh"
     "id" : "03"
      "coverurl" :""
     "name" : "Bermuda Triangle"
     "author" : "Charles Berlitz"
     "id" : "04"
      "coverurl" :""

     "name" : "Eye of the Storm"
     "author" : "Patrick White"
     "id" : "05"
      "coverurl" :""

Step 1: First thing,make sure you have the json library,if not get it from here JSON. and drag all the classes into your project.

Step 2: In the header just include the JSON.h.Now lets get into the coding part.

Step 3: In the viewdidload,lets download the sample.json file,which is kept in the server
NSData* tmpData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"Ur json file url goes here"]];
    NSString* cacheDir = CacheDirectory;
    NSString* cachePath = [cacheDir stringByAppendingPathComponent:@"sample.json"];
    if (!tmpData){
        // attempt to get the data from the cache
        tmpData = [NSData dataWithContentsOfFile:cachePath];
    [tmpData writeToFile:cachePath atomically:YES];
    NSString *jsonString = [[NSString alloc] initWithData:tmpData encoding:NSASCIIStringEncoding];
    NSDictionary *results = [jsonString JSONValue];
    NSArray * json_issues = [NSArray arrayWithArray: [results objectForKey:@"books"]];
    books = [[NSArray alloc] initWithArray:json_issues];

books has all values retrieved from json file.Now thats done,all we need to do is,just need to extract value for each key element from the dictionary object.

-(NSDictionary *)bookAtIndex:(NSInteger)index {
    return [books objectAtIndex:index];
-(NSString *)authorNameAtIndex:(NSInteger)index {
    return [[self bookAtIndex:index] objectForKey:@"name"];
-(NSString *)bookUrlAtIndex:(NSInteger)index {
    return [[self bookAtIndex:index] objectForKey:@"coverurl"];

-(NSString *)bookNameAtIndex:(NSInteger)index {
    return [[self bookAtIndex:index] objectForKey:@"author"];

Step 4: Now passing those strings to UITableView cell is not a big deal.Note that you need include UITableViewDataSource and UITableViewDelegates.
- (UITableViewCell *)tableView:(UITableView *)tableView2 cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *CellIdentifier = @"bookCell";
    UITableViewCell *cell = [tableView2 dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:CellIdentifier];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSURL *url=[NSURL URLWithString:[self bookUrlAtIndex:indexPath.row]];
 //Need to include 
ImageDownloader class
    ImageDownloader *imageView = [[ImageDownloader alloc] initWithFrame:CGRectMake(10, 5,120, 100)];
    //imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.tag = IMAGE_VIEW_TAG;
   [[ImageLoader sharedLoader] cancelLoadingURL:imageView.imageURL];
    //load the image
    imageView.imageURL = url;
     [cell addSubview:imageView];
    UILabel *authorLabel=[[UILabel alloc]initWithFrame:CGRectMake(140, 30, 200, 20)];
    authorLabel.text=[self authorNameAtIndex:indexPath.row];
    authorLabel.textColor=[UIColor blackColor];

    [cell addSubview:authorLabel];
    UILabel *bookLabel=[[UILabel alloc]initWithFrame:CGRectMake(140, 60, 200, 20)];
    bookLabel.text=[self bookNameAtIndex:indexPath.row];
    bookLabel.textColor=[UIColor blackColor];
    bookLabel.textAlignment= NSTextAlignmentLeft;
    bookLabel.font=[UIFont fontWithName:@"Helvetica" size:12];
    [cell addSubview:bookLabel];
    return cell;

Well this is it about reading a simple JSON file. Hope it helps you.You can download the source code here .