Parse JSON from a URL and showing data into UITableView
#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];
table_view.delegate = self;
table_view.dataSource = self;
NSString *jsonString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@“Your Url”]encoding:NSStringEncodingConversionAllowLossy error:nil];//Sample url:http://www.learnswiftonline.com/Samples/subway.json
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]options:0 error:NULL];
NSLog(@"jsonObject=%@", jsonObject);
NSMutableArray *nameArray = [jsonObject objectForKey:@"your key"]; First key from dictionary
name_arr = [[NSMutableArray alloc]init];
num_arr =[[NSMutableArray alloc]init];
NSMutableArray *mean_arr =[[NSMutableArray alloc]init];
for(id item in nameArray)
{
[name_arr addObject:[item objectForKey:@“your key”]];//Any key u need to display
[num_arr addObject:[item objectForKey:@"your key"]];//Any key u need to display
[mean_arr addObject:[item objectForKey:@"your key"]];//Any key u need to display.
}
}
- (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 = @"Cell";
// 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