Ravi
Ravi

Reputation: 898

How to convert NSString to NSArray in Objective C

I need to convert NSString to NSArray. if, few objects contains double quotes, few objects are doesn't contain anything.

NSString *string = @"["Line", "Operations(UK)", "Operations(USA)", "Total of Invoice", "", "Star", "10040101", "31.Jan.2001", "31.Jan.2001", "", "USD", "1653", "28,145.00", 163.48, "Stock, Ms.Pat", "MGR", "14.Nov.2006", "01-000-2210-0000-000", "V1- New York City", 20343, 5]"; 
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e]; 

I have tried to convert using replacing characters like [, ", ] and did "componentsSeparatedByString:" with comma. but its not working properly.

Upvotes: 0

Views: 953

Answers (2)

user3182143
user3182143

Reputation: 9609

I will give you solution with example.I tried this.I got the solution.

NSString *strJson=@"{\"name\":{\"dob\":88,\"age\":61},\"family\" : [{\"location\":\"us\",\"mobile\":\"mobile\"}]}";
NSData *data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",dict);

The output result is

enter image description here

Upvotes: 0

trungduc
trungduc

Reputation: 12154

As i see, you are doing right way to convert from NSString to NSArray. When you declare a NSString, you have to use \" instead of ". It works with me.

NSString *string = @"[\"Line\", \"Operations(UK)\", \"Operations(USA)\", \"Total of Invoice\", \"\", \"Star\", \"10040101\", \"31.Jan.2001\", \"31.Jan.2001\", \"\", \"USD\", \"1653\", \"28,145.00\", 163.48, \"Stock, Ms.Pat\", \"MGR\", \"14.Nov.2006\", \"01-000-2210-0000-000\", \"V1- New York City\", 20343, 5]";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];

Upvotes: 1

Related Questions