//json解析数据
- (void)josnData
{
//1.拿到json文件
NSString *path = [[NSBundle mainBundle] pathForResource:@"us_box.json" ofType:nil];
//2.转换成NSData对象
NSData *data = [NSData dataWithContentsOfFile:path];
//3.json解析成对象
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
//4.解析出来的对象是字典 用字典对象取得里面的数组
NSArray *josnArr = [result objectForKey:@"subjects"];
//5.初始化数组属性
_josnArrM = [NSMutableArray array];
//6.遍历
for (id data in josnArr) {
NSDictionary *dict = [data objectForKey:@"subject"];
josnModel *josn = [josnModel modelWithDict:dict];
[_josnArrM addObject:josn];
}
}
/**数据懒加载*/
- (NSMutableArray *)topData{
if (_topData == nil) {
/**解析出来是字典*/
id result = [JsonData dataWithFileName:@"top250.json"];
/**用字典做key取出来是数组*/
NSArray *array = result[@"subjects"];
/**临时定义可变数组*/
NSMutableArray *arrM = [NSMutableArray array];
for (NSDictionary *dict in array) {
TopModel *model = [TopModel modelWithDict:dict];
[arrM addObject:model];
}
_topData = arrM;
}
NSLog(@"%@", _topData);
return _topData;
}
封装类
+ (id)dataWithFileName:(NSString *)fileName
{
//1.拿到json文件
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
//2.转换成NSData对象
NSData *data = [NSData dataWithContentsOfFile:path];
//3.json解析成对象
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
return result;
}