- (void)viewDidLoad {
[super viewDidLoad];
//1.获取文件的路径
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil];
//2.读取文件内的数据(NSData类型:一般服务器返回的数据类型是NSData)
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
//3.JSON解析
/* 流程:JSON对象转Foundation对象
使用什么类型的Foundation对象的原则: 最外层是中括号/数组,使用NSArray;最外层是大括号/对象,使用NSDictionary
*/
NSError *error = nil;
NSDictionary *dicFromFile = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
//4.取值并验证解析的数据
/* 取值原则:从外往里一层一层
*/
NSNumber *feelsLikeC = dicFromFile[@"FeelsLikeC"];
NSString *tempC = dicFromFile[@"TempC"];
NSArray *requestArray = dicFromFile[@"Request"];
NSDictionary *cityDic = requestArray[0];
NSString *cityName = cityDic[@"city"];
NSDictionary *locationDic = requestArray[1];
NSString *locationStr = locationDic[@"location"];
NSNumber *count = dicFromFile[@"Paging"][@"count"];
NSLog(@"体感温度:%@;天气温度:%@;城市名字:%@;区域名字:%@;页数:%@",feelsLikeC, tempC, cityName, locationStr,count);
}
Json本地解析
最新推荐文章于 2020-05-17 21:49:17 发布