苹果开发 笔记(77)NSJSONSerialization

前端之家收集整理的这篇文章主要介绍了苹果开发 笔记(77)NSJSONSerialization前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

  1. NSString *jsonPath =@"http://www.weather.com.cn/adat/sk/101010100.html";
  2. NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonPath]];
  3. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
  4. NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
  5. NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
  6. NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
  7. NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);

使用NSURLConnection 读取json的信息

  1. NSURLRequest *resuest = [NSURLRequest requestWithURL:[NSURL URLWithString:jsonPath]];
  2.  
  3. [NSURLConnection sendAsynchronousRequest:resuest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError){
  4. NSError *error = nil;
  5. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  6. NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
  7. NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
  8. NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
  9. NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);
  10. }];

NSData 也是使用频繁的一个类,经常会涉及到。

猜你在找的Json相关文章