0

我正在尝试解析一个NSStringswith数组,lat/long coordinates("99.999999","99.999999")然后将其转换为arrayof CLLocations

有没有一种NSString方法可以帮助解决这个问题?

我从外部 REST API 中提取这些坐标,然后JSON先将其转换为字典,然后再转换为数组,这就是我卡住的地方。

有任何想法吗 ?

谢谢!

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

NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);


NSError *myError = nil;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

// Show ALL values coming out of NSJSONSerialization
for(id key in jsonResult) {

    id value = [jsonResult objectForKey:key];

    NSString *keyAsString = (NSString *)key;
    NSString *valueAsString = (NSString *)value;

    NSLog(@"key: %@", keyAsString);
    NSLog(@"value: %@", valueAsString);
}

    NSArray *jsonCoordinates =[jsonResult objectForKey:@"latlng"];


for (id key in jsonCoordinates) {

    //id value = [jsonCoordinates objectForKey:key];

    NSString *keyAsString = (NSString *)key;
    //NSString *valueAsString = (NSString *)value;

    NSLog(@"key: %@", keyAsString);
    //NSLog(@"value: %@", valueAsString);
}


}

日志输出:

2013-04-29 22:23:44.894 RideInfo[9271:c07] 键:(“37.473497”,“-122.213878”)2013-04-29 22:23:44.894 RideInfo[9271:c07] 键:(“37.47346” , "-122.213538")

4

1 回答 1

0

这些值不是字符串(我不明白你为什么假设它们是)。它们是NSArray对象。这些数组可能包含一个NSNumberNSString对象(如果没有看到您收到的实际 JSON,就不可能分辨出哪个),因此它们响应doubleValue消息,该消息将其值为 a double,这适合于CLLocation对象的初始化:

NSMutableArray *locs = [NSMutableArray array];

for (NSString *key in jsonResult) {
    NSArray *pair = jsonResult[key];
    double lat = [pair[0] doubleValue];
    double lon = [pair[1] doubleValue];
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
    [locs addObject:loc];
    // if non-ARC:
    [loc release];
}

这里locs将包含一个对象数组CLLocation

于 2013-04-30T06:15:43.327 回答