1

我正在尝试从 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"    
    }
4

1 回答 1

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
                       }];
于 2013-06-20T23:10:51.073 回答