NSJSONSerialization 是解析json的自带的ios 类,使用它可以解析json 的信息。除了读取xml外,json也是比较常用的一些数据操作。之前用了一下,现在记录一下。
下面记录一下json的页面信息,以获取天气的信息json来解析一下。
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风","WS":"2级","SD":"22%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014"}}
使用NSData 直接来读取远程的数据
NSString *jsonPath =@"http://www.weather.com.cn/adat/sk/101010100.html";
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonPath]];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);
使用NSURLConnection 读取json的信息
NSURLRequest *resuest = [NSURLRequest requestWithURL:[NSURL URLWithString:jsonPath]];
[NSURLConnection sendAsynchronousRequest:resuest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError){
NSError *error = nil;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);
}];
NSData 也是使用频繁的一个类,经常会涉及到。