美文网首页
json解析

json解析

作者: 动感大猴子 | 来源:发表于2018-07-29 23:10 被阅读0次

    @interface ViewController (){

        NSDictionary *_dic;

        UITableView *_tbv;

    }

    @end

    #define TEST_URL @"HTTP://127.0.0.1/1604C.json"

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        _tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];

        _tbv.delegate = self;

        _tbv.dataSource = self;

        [self.view addSubview:_tbv];

        // Do any additional setup after loading the view, typically from a nib.

        NSURLSession *session = [NSURLSession sharedSession];

        NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:TEST_URL] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    #if 0

            //系统自带的方式解析

            self->_dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    #elif 1

            //SBJson

            SBJsonParser *js = [[SBJsonParser alloc]init];

            self->_dic = [js objectWithData:data];

    #elif 0

            //json kit

            self->_dic = [data objectFromJSONData];

    #endif

            //回到主线程

            dispatch_async(dispatch_get_main_queue(), ^{

                [self->_tbv reloadData];

            });

        }];

        [task resume];

    }

    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

        return _dic.allKeys.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 *identifier = @"identifier";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

        if (cell == nil) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];

        }

        NSString *key = [_dic.allKeys objectAtIndex:indexPath.section];

        cell.textLabel.text = [[[_dic objectForKey:key]objectAtIndex:indexPath.row]objectForKey:@"name"];

        cell.detailTextLabel.text = [[[_dic objectForKey:key]objectAtIndex:indexPath.row]objectForKey:@"like"];

        return cell;

    }

    -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

        return [_dic.allKeys objectAtIndex:section];

    }

    相关文章

      网友评论

          本文标题:json解析

          本文链接:https://www.haomeiwen.com/subject/cxtejftx.html