我正在尝试从 json 中解析一些值。我设法获得 results.geometry.location 的值。如果参数失败,服务器返回一个值为 2 的 json。结果为空 [],状态为“一些错误”。
url = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",postalCode];
NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding];
NSArray* myResults = [NSJSONSerialization JSONObjectWithData:jsonDataString options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
latLon =[myResults valueForKeyPath:@"results.geometry.location"];
generalDict = (NSDictionary *)[latLon objectAtIndex:0];
NSLog(@"%@",[generalDict objectForKey:@"lat"]);
这很困惑。我试过:
latLon =[myResults valueForKeyPath:@""];
generalDict = (NSDictionary *)[latLon objectAtIndex:0];
NSLog(@"%@",[generalDict objectForKey:@"status"]);
但是没有用。我怎样才能得到状态的值(value)。这是请求无效时的样子:
{
"results" : [],
"status" : "ZERO_RESULTS"
}
最佳答案
myResults 是字典,不是数组。我想你想要这样的东西:
NSURL *url = [NSURL urlWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",postalCode];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSDictionary *jsonPayload = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
error:nil];
NSString *status = [jsonPayload objectForKey:@"status"];
//Check for error status
NSArray *resultsArray = [jsonPayload objectForKey:@"results"];
//Do whatever you want with your results array
}];
关于ios - iOS 6 中的 JSON 解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17225226/