zoukankan      html  css  js  c++  java
  • iOS学习—JSON数据解析

     

     

     关于在iOS平台上进行JSON解析,已经有很多第三方的开源项目,比如TouchJson,JSONKit,SBJon等,自从iOS5.0以后,苹果SDK推出了自带的JSON解决方案NSJSONSerialization,这是一个非常好用的JSON生成和解析工具,效率也是比其他第三方开源项目的高很多,详情可看下图。

     

     

     

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

    Json数据封包

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


     

    Json数据解析

     


     
    1. NSError *error;  
    2.     //加载一个NSURL对象  
    3.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.html"]];  
    4.     //将请求的url数据放到NSData对象中  
    5.     NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
    6.     //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中  
    7.     NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];  
    8.     NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];  
    9.     NSString *text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];  
    10.     NSLog(@"weatherInfo:%@", text );  
  • 相关阅读:
    如何实时抓取动态网页数据?
    产品经理面试——简历填写
    项目章程
    IDEA 必要配置
    项目章程
    基础知识02 零基础入门学习汇编语言02
    基础知识03 零基础入门学习汇编语言03
    进制转换教程
    基础知识04 零基础入门学习汇编语言04
    基础知识01 零基础入门学习汇编语言01
  • 原文地址:https://www.cnblogs.com/LiLihongqiang/p/5556665.html
Copyright © 2011-2022 走看看