Search code examples
ioscocoa-touchnsstringnsarraytext-parsing

Convert NSString representing an array of arrays of numbers to NSArray


I am receiving a string in my request; the string is a list of pairs of numbers, grouped with square brackets. (The list represents polygons to display inside my app.)

I need to convert it to an NSArray and parse all the numbers into coordinates.

The received string is

[[[53.502483, -113.420593], [53.503429, -113.421527], [53.503491, -113.421673], [53.503002, -113.42164], [53.502719, -113.421426], [53.502483, -113.420593]]]

All the examples I've found are just to convert a single list in text to NSArray. I couldn't find anything where there are multiple arrays in the string.


Solution

  • The string looks like valid JSON, so...

    NSError *error;
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];
    

    Will give the array, provided string contains the input. If it's coming from a web request, you can save a step and convert the request's NSData directly.