iOS学习——JSON数据解析(十一)

     在以前的iOS学习——xml数据解析(九)》介绍了xml数据解析,这一篇简单介绍一下Json数据解析。JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,很是适合于服务器与客户端的交互,Json语法参考关于在iOS平台上进行JSON解析,已经有不少第三方的开源项目,好比TouchJson,JSONKit,SBJon等,自从iOS5.0之后,苹果SDK推出了自带的JSON解决方案NSJSONSerialization,这是一个很是好用的JSON生成和解析工具,效率也是比其余第三方开源项目的高不少,详情可看下图html

 

图片详情可查看java

 

NSJSONSerialization提供了Json数据封包、Json数据解析,NSJSONSerialization将JSON数据转换为NSDictionary或NSArray解包方法,将NSDictionary、NSArray对象转换为JSON数据(能够经过调用isValidJSONObject来判断NSDictionary、NSArray对象是否能够转换为JSON数 据)封包。这一篇将作简单介绍。android


Json数据封包

 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",@"value3",@"key3", nil];
    // isValidJSONObject判断对象是否能够构建成json对象
    if ([NSJSONSerialization isValidJSONObject:dic]){
        NSError *error;
        // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白,使输出更具可读性。
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }



Json数据解析

 

NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.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"];
    NSString *text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气情况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
    NSLog(@"weatherInfo:%@", text );


/**
* @author 张兴业
*  iOS入门群:83702688
*  android开发进阶群:241395671
*  个人新浪微博:@张兴业TBOW
*/

参考:ios

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946-CH1-DontLinkElementID_1web

http://www.w3school.com.cn/json/json

http://www.ibm.com/developerworks/cn/web/wa-lo-json/服务器

http://blog.sina.com.cn/s/blog_7018d3820101bdqz.htmlapp

相关文章
相关标签/搜索