Oc Json解析 表格

Json 三种方法:JSONKit(第三方)、SBJson(第三方)、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解析 表格)