Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Define "custom objects". –  Hot Licks Jul 23 '13 at 12:17
    
what is the problem do you have in this given code?? –  Armaan Stranger Jul 23 '13 at 12:19
    
I get empty result –  revolutionkpi Jul 23 '13 at 12:21
    
Does your array contains data?? –  Armaan Stranger Jul 23 '13 at 12:22
    
See this question similar to yours : stackoverflow.com/questions/9139454/… –  Armaan Stranger Jul 23 '13 at 12:23
add comment

3 Answers

This is process is really simple now, you don't have to used 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];
share|improve this answer
add comment

Try like this,

- (NSString *)JSONRepresentation {
    SBJsonWriter *jsonWriter = [SBJsonWriter new];    
    NSString *json = [jsonWriter stringWithObject:self];
    if (!json)

    [jsonWriter release];
    return json;
}

then call this like,

NSString *jsonString = [array JSONRepresentation];

Hope it will helps you...

share|improve this answer
    
I suspect that the problem is the "custom objects", which the writer must somehow know how to interpret. Much easier if everything is in arrays/dictionaries. –  Hot Licks Jul 23 '13 at 12:46
    
The above code is broken. Either it will fail to compile under ARC, because you call release, or it will leak memory because you only release the writer if you fail to JSONify self. –  Stig Brautaset Aug 8 '13 at 21:11
add comment

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 json;
}

@end
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.