Reputation: 1922
What's the best way to convert a JavaScript array (saved in an NSString) with this format:
["Hello", "World"]
in an NSArray?
Thanks
Upvotes: 0
Views: 758
Reputation: 1313
Try this!
NSString * jsonString = @"[\"Hello\",\"World\"]";
NSError * serializationError = nil;
NSArray * array = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&serializationError];
NSLog(@"NSArray - %@ \n error - %@", array, serializationError.localizedDescription);
Log:
NSArray - ( Hello, World ) error - (null)
Upvotes: 1
Reputation: 1922
As Felix suggested, a JavaScript array is actually a JSON array.
So I solved doing some JSON parsing. Thank you!
NSError *e;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:[arrayString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&e];
Upvotes: 2
Reputation: 3154
I can't tell exactly what your input string is, but you can use NSString's componentsSeparatedByString function to split up a string into an array of substrings.
Upvotes: 0