#import "ViewController.h"#import "JSONKit.h"#import "SBJsonParser.h"@interface ViewController (){
UITableView *_table;
NSMutableDictionary *_dic;
}
@end
#define JSON_URL @"http://127.0.0.1/1509E.json"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化表格
_table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
_table.delegate = self;
_table.dataSource = self;
[self.view addSubview:_table];
_dic = [[NSMutableDictionary alloc]init];
NSURL *url = [NSURL URLWithString:JSON_URL];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"异步加载数据----->%@",response.MIMEType);
if ([response.MIMEType isEqualToString:@"application/json"]) {
#if 0
// 初始化一个 SBJsonParser 的对象
SBJsonParser *parser = [[SBJsonParser alloc]init];
_dic = [parser objectWithData:data];
NSLog(@"解析数据---->>>%@",_dic);
#elif 0
// JSONKit
_dic = [data objectFromJSONData];
#elif 1
// 系统自带的 Json 解析
_dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
#endif
// 回到主线程刷新表格
dispatch_async(dispatch_get_main_queue(), ^{
[_table reloadData];
});
}
}];
}
// 设置表格分区
- (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 *reuseID = @"";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseID];
}
NSArray *arr = [_dic objectForKey:[_dic.allKeys objectAtIndex:indexPath.section]];
cell.textLabel.text = [[arr objectAtIndex:indexPath.row]objectForKey:@"name"];
cell.detailTextLabel.text = [[arr objectAtIndex:indexPath.row]objectForKey:@"ids"];
return cell;
}