Convert an iOS objective c object to a JSON string

EDIT: I have made a dummy app that should be a good example for you.

I create a Message class from your code snippet;

//Message.h
@interface Message : NSObject {
    NSString *from_;
    NSString *date_;
    NSString *msg_;
}

@property (nonatomic, retain) NSString *from;
@property (nonatomic, retain) NSString *date;
@property (nonatomic, retain) NSString *msg;

-(NSDictionary *)dictionary;

@end

//Message.m
#import "Message.h"

@implementation Message

@synthesize from = from_;
@synthesize date = date_;
@synthesize msg = mesg_;

-(void) dealloc {
    self.from = nil;
    self.date = nil;
    self.msg = nil;
    [super dealloc];
}

-(NSDictionary *)dictionary {
    return [NSDictionary dictionaryWithObjectsAndKeys:self.from,@"from",self.date,    @"date",self.msg, @"msg", nil];
}

Then I set up an NSArray of two messages in the AppDelegate. The trick is that not only does the top level object (notifications in your case) need to be serializable but so do all the elements that notifications contains: Thats why I created the dictionary method in the Message class.

//AppDelegate.m
...
Message* message1 = [[Message alloc] init];
Message* message2 = [[Message alloc] init];

message1.from = @"a";
message1.date = @"b";
message1.msg = @"c";

message2.from = @"d";
message2.date = @"e";
message2.msg = @"f";

NSArray* notifications = [NSArray arrayWithObjects:message1.dictionary, message2.dictionary, nil];
[message1 release];
[message2 release];


NSError *writeError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON Output: %@", jsonString);

@end

The output when I run the application is thus:

2012-05-11 11:58:36.018 stack[3146:f803] JSON Output: [
{
“msg” : “c”,
“from” : “a”,
“date” : “b”
},
{
“msg” : “f”,
“from” : “d”,
“date” : “e”
}
]

ORIGINAL ANSWER:

Is this the documentation you are looking for?

Leave a Comment