iOS5自带解析类NSJSONSerialization解析json

来源:互联网 发布:.sql注释 编辑:程序博客网 时间:2024/05/16 17:40

作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式。(http://www.bejson.com/可以对json数据进行格式化从iOS5开始,APPLE提供了对json的原生支持(NSJSONSerialization)。

一、用NSJSONSerialization解析json要求

我们能利用 NSJSONSerialization将JSON转换成Foundation对象,也能将Foundation对象转换成JSON,转换成JSON的对象必须具有如下属性:

  • 顶层对象必须是NSArray或者NSDictionary
  • 所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例
  • 所有NSDictionary的key必须是NSString类型
  • 数字对象不能是非数值或无穷
二、使用IOS5自带解析类NSJSONSerialization方法解析:(无需导入包,IOS5支持,低版本IOS不支持)

- (IBAction)onBtnClicked:(id)sender {    NSError *error;    //加载一个NSURL对象    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];    //将请求的url数据放到NSData对象中    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];    //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中    NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];    NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];    txtView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];    NSLog(@"weatherInfo字典里面的内容为--》%@", weatherDic );}


0 0
原创粉丝点击