您的位置:首页 > 移动开发 > IOS开发

苹果开发 笔记(77)NSJSONSerialization

2015-09-18 20:01 585 查看
NSJSONSerialization 是解析json的自带的ios 类,使用它可以解析json 的信息。除了读取xml外,json也是比较常用的一些数据操作。之前用了一下,现在记录一下。

下面记录一下json的页面信息,以获取天气的信息json来解析一下。

[code]{"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 直接来读取远程的数据

[code] 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的信息

[code] 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 也是使用频繁的一个类,经常会涉及到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: