iOS中NSJSONSerialization解析JSON数据暨google地理信息处理案例
在iOS开发中,涉及到从网络取得json格式的数据处理工作时,我们会想到很多开源的第三方包,如SBJSON。在iOS5开始,也增加了对json格式数据的处理能力,增加的类是NSJSONSerialization。
使用NSJSONSerialization,可以分析各种复杂格式json数据。
使用的类方法是+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error。
根据不同data的结构,设置不同的option。这里option有三类:NSJSONReadingMutableContainers, NSJSONReadingMutableLeaves , NSJSONReadingAllowFragments。
apple文档对这三种方法做了说明。
1、NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
2、NSJSONReadingMutableLeaves
Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
3、NSJSONReadingAllowFragments
Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
Available in iOS 5.0 and later.
我就http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true这个链接做了测试。这是google的地理信息api,根据地点得到经纬度等信息。
这个url得到的json格式的结果如下所示:
-(void)parseJson:(NSString *)addr{ //The URL of JSON service NSString *_urlString = @"http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true"; NSString *_dataString = [[NSString alloc] initWithData:[_urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding]; //_dataString=[NSString stringWithUTF8String:[_urlString UTF8String]]; NSURL *_url = [NSURL URLWithString:_dataString]; NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:_url]; [_request setValue:@"accept" forHTTPHeaderField:@"application/json"]; [NSURLConnection sendAsynchronousRequest:_request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) { //block define statment NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; int responseStatusCode = [httpResponse statusCode]; NSLog(@"response status code is %d",responseStatusCode); NSError *_errorJson = nil; NSDictionary *resultsDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; if (_errorJson != nil) { NSLog(@"Error %@", [_errorJson localizedDescription]); } else { NSString *resultStatus = [resultsDic objectForKey:@"status"]; if ([resultStatus isEqualString:@"OK"]) { NSArray *resultsArr = [resultsDic objectForKey:@"results"]; //Do something with returned array for (NSDictionary * resultDetailDic in resultsArr) { NSDictionary * locationDic=[[resultDetailDic objectForKey:@"geometry"] objectForKey:@"location"]; NSString * lat=[locationDic objectForKey:@"lat"]; NSString * lng=[locationDic objectForKey:@"lng"]; dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"locationDic.lat 是--->%@\n",lat); NSLog(@"locationDic.lng 是--->%@\n",lng); });// dispatch async main } } } }];}
通过这段代码,我们可以实现异步读取,json格式数据分析。这些操作都不需要调用任何第三方代码,仅仅使用了apple自身提供的功能。这样做的好处,便于维护和升级。