Parse JSON from a file and showing data into UITableView
To create a json file in the project,
File-->Other-->Empty as .json file and write the below content in the file and run.
{
"Details":
[
{
"Name": "BatMan",
"Native": "Gotham"
}
]
}
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
IBOutlet UITableView *table_view;
NSMutableArray *name_arr;
NSMutableArray *num_arr;
}
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSMutableArray *nameArray = [json objectForKey:@"Details"];
name_arr = [[NSMutableArray alloc]init];
num_arr =[[NSMutableArray alloc]init];
for(id item in nameArray)
{
[name_arr addObject:[item objectForKey:@"Name"]];
[num_arr addObject:[item objectForKey:@"Native"]];
}
table_view.delegate = self;
table_view.dataSource = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [name_arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"HistoryCell";
// Similar to UITableViewCell, but
UITableViewCell *cell = (UITableViewCell *)[table_view dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
NSString *name_str=[name_arr objectAtIndex:indexPath.row];
NSString *ver_str=[num_arr objectAtIndex:indexPath.row];
cell.textLabel.text =name_str;
cell.detailTextLabel.text=ver_str;
return cell;
}

Comments
Post a Comment