编辑:我制作了一个虚拟应用程序,对你来说应该是一个很好的例子。
我从您的代码片段创建了一个 Message 类;
//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];
}
然后我在 AppDelegate 中设置了两个消息的 NSArray。诀窍是不仅顶级对象(在您的情况下为通知)需要可序列化,而且通知包含的所有元素也需要可序列化:这就是我在 Message 类中创建字典方法的原因。
//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
因此,当我运行应用程序时的输出是:
2012-05-11 11:58:36.018 堆栈[3146:f803] JSON 输出:[{“msg”:“c”,“from”:“a”,“date”:“b”},{“msg” :“f”,“来自”:“d”,“日期”:“e”}]
原始答案:
这是您要查找的文档吗?