iOS 数据解析(3)

原生网络数据解析:

1、第一种方法:

    NSURL *url =[NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"];
    NSData *jsondata =[NSData dataWithContentsOfURL:url];
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments error:nil];
    NSDictionary *dic =(NSDictionary*)jsonObj;
    NSDictionary *dic1 =[dic objectForKey:@"weatherinfo"];
    NSLog(@"%@", [dic1 objectForKey:@"city"]);

2、第二种方法:

    NSURL *url =[NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"];
    NSString *jsonStr =[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    NSData *jsondata =[jsonStr dataUsingEncoding:NSUTF8StringEncoding];

    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments error:nil];
    NSDictionary *dic =(NSDictionary*)jsonObj;
    NSDictionary *dic1 =[dic objectForKey:@"weatherinfo"];
    NSLog(@"%@", [dic1 objectForKey:@"city"]);



3、第三种方法:

   NSURL *url =[NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    //参数1:请求数据   参数2:请求之后返回的信息    参数3:错误信息
    NSData *jsondata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  //苹果已经放弃方法
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments error:nil];
    NSDictionary *dic =(NSDictionary*)jsonObj;
    NSDictionary *dic1 =[dic objectForKey:@"weatherinfo"];
    NSLog(@"%@", [dic1 objectForKey:@"city"]);





  最主要的是工程中别忘在plist文件中添加对http允许运行的代码

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值