create a json string from NSArray

revolutionkpi picture revolutionkpi · Jul 23, 2013 · Viewed 35.7k times · Source

In my iPhone aplication I have a list of custom objects. I need to create a json string from them. How I can implement this with SBJSON or iPhone sdk?

 NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:@"Event" where:@"isForUpload" is:[NSNumber numberWithBool:YES]];
    SBJsonWriter *writer = [[SBJsonWriter alloc] init];  
    NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];

and i get empty result.

Answer

Thilina Hewagama picture Thilina Hewagama · Nov 27, 2013

This process is really simple now, you don't have to use external libraries, Do it this way, (iOS 5 & above)

NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];