OC Json解析 表格

JSON 三种方法: (1)JSONKit(第三方)、
(2)SBJson(第三方)、
(3)NSJSONSerialization

手写Json文件

{
    "一组":[
             {"name":"姚明","like":"篮球"},
             {"name":"张继科","like":"乒乓球"},
             {"name":"林丹","like":"羽毛球"}
             ],
    
    "二组":[
             {"name":"丁俊晖","like":"台球"},
             {"name":"刘洋","like":"铅球"}
             ],
    
    "三组":[
             {"name":"郎平","like":"排球"},
             {"name":"贾天子","like":"足球"},
             {"name":"李娜","like":"网球"},
             {"name":"关之琳","like":"高尔夫球"}
             ]
    
}
ViewController.m

#import "ViewController.h"
#import "JSONKit.h"
#import "SBJson.h"
@interface ViewController ()
{
    UITableView *_table;
   NSMutableDictionary *dic;
}

@end
#define TEST_URL @"http://127.0.0.1/text.json"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *url = [NSURL URLWithString:TEST_URL];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 
#if 0
        dic =  [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",dic);
        
        
#elif 0
        SBJsonParser *parser = [[SBJsonParser alloc]init];
        dic = [parser objectWithData:data];
        
#elif 1
        dic  = [data objectFromJSONData];
        NSLog(@"%@",dic);
        
#endif
       
    }];
    [task resume];
    
    _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dic.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key  = [dic.allKeys objectAtIndex:section];
    return [[dic objectForKey:key]count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"cellid";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
    }
    
    NSString *key = [dic.allKeys objectAtIndex:indexPath.section];
    cell.textLabel.text = [[dic[key]objectAtIndex:indexPath.row]objectForKey:@"name"];
    cell.detailTextLabel.text = [[dic[key]objectAtIndex:indexPath.row]objectForKey:@"like"];
    
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [dic.allKeys objectAtIndex:section];
}
@end

你可能感兴趣的:(OC Json解析 表格)