处理从网络中获取的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的操作了!)
}