将NSString解析为NSArray

时间:2015-04-20 10:48:28

标签: ios objective-c nsstring nsarray

我正在尝试将NSString解析为NSArray,但无法取得任何成功。这是我的字符串:NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";

我希望这个字符串映射到NSArray。

NSArray *tempArray = points;

3 个答案:

答案 0 :(得分:2)

好的,代码高尔夫(未经测试):

NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
                                                       options:kNilOptions
                                                         error:&error];
for (NSArray *point in pointsArray) {
    NSAssert([point count] == 2, @"Invalid point");
    // do thing with point
    CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}

答案 1 :(得分:0)

你可以尝试一下吗,它可以解决你的问题,

NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:@","];
NSLog(@"%@",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];

NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
    [yourarray addObject:[NSString stringWithFormat:@"%@,%@",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(@"%@",yourarray);

快乐编码!!

答案 2 :(得分:0)

该字符串看起来像JSON,因此您可以使用NSJSONSerialization

NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];