Saturday, 21 July 2012

JSON Using Local File Implementation in Xcode

Step1: Create A Xcode project in Name of Json

Step2: JSON Files Download Link : http://www.mediafire.com/?iw9p1bap515cojn

Step3: Import the Downloaded file into your Project.

Step4: Create the json file in Name of Asan.json.

Step5: Asan.json Write a Below Coding and Save File.

{
    "Details":
    [
        {
            "Name": "Asan",
            "Native": "From TVL"
        },
        {
            "Name": "Elavarasan",
            "Native": "From Ariyalur"
        },
        {
            "Name": "Santhosh",
            "Native": "From Vellore"
        }
    ]
}


Step6: Asan.json file is implemented to project.

Step7: open .h File and import the Codings

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

    NSArray *tableData;
}

@property (nonatomic, retain) NSArray *tableData;

@end


Step8: open .m File and import the Codings

#import "JSON.h"

@synthesize tableData;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Download JSON
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Asan" ofType:@"json"]; 
    NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
    
    // Create parser
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
[parser release], parser = nil;
    
    // Set tableData
    [self setTableData:[data objectForKey:@"Details"]];
    
}


// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Change UITableViewCellStyle
        cell = [[[UITableViewCell alloc
                 initWithStyle:UITableViewCellStyleSubtitle 
                 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Get item from tableData
    NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
    // Set text on textLabel
    [[cell textLabel] setText:[item objectForKey:@"Name"]];
    // Set text on detailTextLabel
    [[cell detailTextLabel] setText:[item objectForKey:@"Native"]];
    
    return cell;
}


- (void)viewDidUnload
{
    [self setTableData:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [tableData release];
    [super dealloc];
}


Step9: Build and Run the Xcode Application





No comments: