編集:私はあなたのための良い例であるべきダミーアプリを作ってきました。
コードスニペットから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に2つのメッセージのNSArrayを設定しました。そのトリックは、トップレベルのオブジェクト(あなたの場合の通知)はシリアライズ可能である必要があるだけでなく、通知に含まれるすべての要素がそうであるということです:メッセージクラスの辞書メソッドを作成した理由
//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
Iアプリケーションを実行出力は、このようになる:
2012-05-11 11:58:36.018スタック[3146:F803] JSON出力:[ { "MSG": " C " "から": "A"、 "日付": "B" }、 { "MSG": "F"、 "から": "D"、 "日付":" E " } ]
オリジナル回答:
thisは、お探しのドキュメントですか?
OPは – user439407
ダモ(静的メソッドは、トリックを行います)最初の辞書に彼のオブジェクトを変換する必要がありますが、前方にかなりストレートのthatsます:そのページはJSONにカスタムクラスの配列の変換について説明していません。それが私が見つけようとしていることです。 –
あなたのクラスivarsがすべてNSStringの場合、それはちょうど魔法のように動作するはずです....警告:私はこれを試していません。 – Damo