Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a json string from NSArray

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.

like image 249
revolutionkpi Avatar asked Jul 23 '13 12:07

revolutionkpi


2 Answers

I love my categories so I do this kind of thing as follows

@implementation NSArray (Extensions)  - (NSString*)json {     NSString* json = nil;      NSError* error = nil;     NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];     json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];      return (error ? nil : json); }  @end 
like image 25
Damo Avatar answered Oct 17 '22 07:10

Damo


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]; 
like image 112
Thilina Chamath Hewagama Avatar answered Oct 17 '22 07:10

Thilina Chamath Hewagama