0

I'm trying to send an array in post JSONModel call. I need convett my array to NSString and send the array in format:

[1, 2, 3] 

but when I convert this to NSString and print my array, this has the format:

(1, 2, 3)


NSMutableArray *array= [NSMutableArray arrayWithObjects:@"1", @"2",@"3",@"4", nil];
NSString *arraString = [NSString stringWithFormat:@"%@", arr];
NSLog(@"%@",arraString);

How can I create this with [] format?

user3745888
  • 6,143
  • 15
  • 48
  • 97

2 Answers2

1
NSMutableArray *array= [NSMutableArray arrayWithObjects:@"1", @"2",@"3",@"4", nil];
NSData *jsond = [NSJSONSerialization dataWithJSONObject: array options:NSJSONWritingPrettyPrinted error:NULL];
NSString *json = [[NSString alloc] initWithData:jsond encoding:NSUTF8StringEncoding];

NSLog(@"%@", json);
TyR
  • 718
  • 4
  • 9
  • How could I avoid the \n when I add my json array serialized to params in my call?, I'm getting: "[\n 1,\n 2,\n 3,\n 4\n]" instead of [ 1, 2, 3, 4] – user3745888 Sep 16 '16 at 20:22
  • Remove the 'pretty print' option from my code snippet and replace it with a 0. – TyR Sep 16 '16 at 20:25
  • That's NSData yo (and probably doesn't actually contain a t)... Convert it to an NSString and print it. See last line of my code) – TyR Sep 16 '16 at 21:12
  • ...actually the second-to-last line (beginning with NSString *json...) – TyR Sep 16 '16 at 21:25
0

What you can do is

NSString *joinedString = [array componentsJoinedByString:@","];
NSString *arraString = [NSString stringWithFormat:@"(%@)", joinedString];

Hope this will fix your problem

Kuntal Gajjar
  • 792
  • 6
  • 12