使用NSJSONSerialization解析从网络中获取的数据

处理从网络中获取的Json数据,现在以某网站的的天气数据为例,代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

    [self loadMyJsonData];

    // Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    

    // Dispose of any resources that can be recreated.

}


-(void)loadMyJsonData{

    //地址

    NSString *urlStr=@"http://m.weather.com.cn/atad/101190101.html";

    NSURL *url=[NSURL URLWithString:urlStr];

    NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];

    NSError *error;

    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    if (data!=nil) {

        //说明已经请求到数据

        self.view.backgroundColor=[UIColor greenColor];

        //处理Json数据

        [self handleJsonData:data];

    }else if ((data == nil && !error)){

            //说明求情还是正确的,但是只是没有数据

        self.view.backgroundColor=[UIColor yellowColor];

    

    }else{

        //说明发送请求错误,发出红色警告

        self.view.backgroundColor=[UIColor redColor];

        //打印错误

        NSLog(@"%@",error.localizedDescription);

    }


}

//处理得到的Json数据的办法

-(void)handleJsonData:(NSData *)data{


    //Json解析得到的数据是个NSArray类型

    NSArray *arr=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

    //把得到的arr输出

    NSLog(@"%@",arr);

    //或者也也可提取需要的内容(这就是Foundation的操作了!)

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值