第五步,根据字典信息,得到每一个key对应的对象是一个字符串
这个字符串就是我们最终要的数据。
如果觉得这种数据分析对数据结构关联太密切,谓之曰不够强壮,你可以做一些isKindOfClass判断。
全部代码如下:
-(void)parseJson:(NSString *)addr
{
//The URL of JSON service
NSString *_urlString = @"?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自身提供的功能。这样做的好处,便于维护和升级。