一.根据UI写一个简单的JSONDemo,如图
在http://json.cn/#中从内部往外写,写好后在http://www.bejson.com/中获取合适的格式。然后存放到txt中
二.读取JSON,并展示到tableView
1.读取JSON
1.1 获取JSON路径
JSON在沙盒中
```
NSString *jsonPath = [NSHomeDirectory() stringByAppendingPathComponent:@“Documents/JSON.txt”];
```
JSON在项目中
```
NSString *jsonPath = [[NSBundle mainBundle]pathForResource:@“JSON”ofType:@“txt”];
```
1.2 获取路径中JSON中的数据
```
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
```
1.3 解析JSON,并判断JSON的格式
```
id jsonObject = [NSJSONSerialization JSONbjectWithData:data options:NSJSONReadingMutableContainers error:&err];
if(jsonObject != nil && err == nil){
if (jsonObject isKindOfClass:[NSDictionary class]){
return (NSDictionary *)jsonObject;
}else if (jsonObject isKindOfClass:[NSArray class]){
return (NSArray *)jsonObject;
}else{
return nil;
}
}
```
1.4 将得到的JSON数据封装成Model,放到全局数组中,刷新tableView(代码参考下方git中的代码)
2.设置tableView
2.1 注册自定义XIB创建的cell
```
[_tableView registerNib:[UINib nibWithNibName:@“MyCell”bundle:nil]forCellReuseIdentifier:@“cell”];
```
2.2 设置布尔数组,用来记录每个区被点中了展开这个区
定义布尔数组
```
BOOL *_isOpen;
```
初始化布尔数组
```
_isOpen = malloc(sizeOf(BOOL)*_total.count);
memset(_isOpen,0,sizeOf(BOOL)*_total.count);
```
2.3 给cell上的button绑定方法刷新该区
```
_isOpen[button.tag] = !_isOpen[button.tag];
```
动态刷新某个区
```
NSIndexSet *set = [NSIndexSet indexSetWithIndex:button.tag-1];
[_tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
```
2.4 在numberOfRowsInSection:方法中判断并刷新cell个数
```
if(_isOpen[section]){
return _currentCellCount;
}
return 1;
```
整体效果图如下: