4

我正在从谷歌地图中提取一些数据,但我似乎无能为力。这是我的代码:

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection  {

//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];

//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];

NSLog(@"%@", [jsonArray objectAtIndex:0]);

}

如果我记录 jsonArray.count 我得到 2,这似乎是正确的,因为谷歌将在顶层返回结果和状态。但是,如果我尝试获取对象 0,它会崩溃。如果我尝试做这样的事情,它也会崩溃:

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection  {

//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];

//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];

for(NSDictionary* thisLocationDict in jsonArray) { 

    NSString* location = [thisLocationDict objectForKey:@"results"];
    [locationData addObject:location];
}
}

我使用此代码从 Twitter 毫无问题地获取数据。我在控制台中遇到的错误是我试图获取一个字符串对象:

-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x798a270

这是谷歌发送给我的json:

类型=(地方,政治);}, { "long_name" = "Upper Merion"; "short_name" = "Upper Merion"; 类型=(“administrative_area_level_3”,政治);}, { "long_name" = 蒙哥马利; "short_name" = 蒙哥马利;类型=(“administrative_area_level_2”,政治);}, { "long_name" = 宾夕法尼亚州;“短名称” = PA;类型=(“administrative_area_level_1”,政治);}, { "long_name" = "美国"; "short_name" = 美国;类型=(国家,政治);}, { "long_name" = 19406; “短名称” = 19406;类型=(“邮政编码”);}); "formatted_address" = "2900 Horizo​​n Dr, King of Prussia, PA 19406, USA"; 几何={位置={纬度=“40.0896985”;lng = "-75.341717"; }; “location_type”=屋顶;视口 = { 东北 = { 纬度 = "40.09104748029149"; lng = "-75.34036801970849"; }; 西南={纬度=“40。

和我传递的网址:

http://maps.googleapis.com/maps/api/geocode/json?address=2900+Horizon+Drive+King+of+Prussia+,+PA&sensor=false

知道我做错了什么吗?

4

1 回答 1

3

与您从 google 获得的数据不同的是,它由键分开,例如results, geometry, formatted_address...

你应该这样做:

NSError *error;

NSString *lookUpString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&components=country:AU&sensor=false", self.searchBar.text];

lookUpString = [lookUpString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];

self.locationArray = [[jsonDict valueForKey:@"results"] valueForKey:@"formatted_address"];

int total = self.locationArray.count;
NSLog(@"locationArray count: %d", self.locationArray.count);

for (int i = 0; i < total; i++)
{
    NSString *statusString = [jsonDict valueForKey:@"status"];
    NSLog(@"JSON Response Status:%@", statusString);

    NSLog(@"Address: %@", [self.locationArray objectAtIndex:i]);

}
于 2013-04-29T23:36:01.780 回答