我试图从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"]);
但不起作用。我怎样才能获得状态的价值。这是请求无效时的样子:
{
"results" : [],
"status" : "ZERO_RESULTS"
}
答案 0 :(得分:1)
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
}];