编辑:我做了一个虚拟的应用程序,应该是您的一个很好的例子。
我根据您的代码片段创建一个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类中创建了
dictionary 方法。
//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 stack [3146:f803] JSON输出:[{“ msg”:“ c”,“ from”:“
a”,“ date”:“ b”},{“ msg” :“ f”,“ from”:“ d”,“ date”:“ e”}]
原始答案:
是这个你正在寻找的文件?
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)