2012-05-11 14 views
23

へのiOS Objective Cのオブジェクトに変換します。 NSMutableArrayのすべてのインスタンスをiOS 5 SDKの新しいJSONSerialization APIを使用してJSONファイルにシリアル化する必要があります。これどうやってするの ?は、私のような客観Cクラスを持って、</p> <pre><code>@interface message : NSObject { NSString *from; NSString *date; NSString *msg; } </code></pre> <p>私はこのメッセージクラスのインスタンスのNSMutableArrayのを持っているJSON文字列

NSArrayの要素の各インスタンスを反復処理することによって、各キーのNSDictionaryを作成していますか?誰かがこれを解決する方法のコードで助けることができますか? 「JSON」は結果をサーバー側の呼び出しにスキューし、シリアル化ではなくデータを転送するため、Googleで良い結果を得ることはできません。どうもありがとう。

EDIT:

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

答えて

35

編集:私はあなたのための良い例であるべきダミーアプリを作ってきました。

コードスニペットから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は、お探しのドキュメントですか?

+0

OPは – user439407

+1

ダモ(静的メソッドは、トリックを行います)最初の辞書に彼のオブジェクトを変換する必要がありますが、前方にかなりストレートのthatsます:そのページはJSONにカスタムクラスの配列の変換について説明していません。それが私が見つけようとしていることです。 –

+0

あなたのクラスivarsがすべてNSStringの場合、それはちょうど魔法のように動作するはずです....警告:私はこれを試していません。 – Damo

8

これで簡単にJSONModelを使用してこの問題を解決できます。 JSONModelは、Classに基づいてオブジェクトを総称的にシリアライズ/逆シリアル化するライブラリです。 int,shortfloatのような非nsobjectベースのプロパティを使用することもできます。また、ネストされた複合JSONを処理することもできます。あなたのエラーチェックを処理します。

デシリアライズ例

#import "JSONModel.h" 

@interface Message : JSONModel 
@property (nonatomic, strong) NSString* from; 
@property (nonatomic, strong) NSString* date; 
@property (nonatomic, strong) NSString* message; 
@end 

実装ファイルで:

#import "JSONModelLib.h" 
#import "yourPersonClass.h" 

NSString *responseJSON = /*from somewhere*/; 
Message *message = [[Message alloc] initWithString:responseJSON error:&err]; 
if (!err) 
{ 
    NSLog(@"%@ %@ %@", message.from, message.date, message.message): 
} 

シリアライズ例ヘッダファイルです。実装ファイル内:

#import "JSONModelLib.h" 
#import "yourPersonClass.h" 

Message *message = [[Message alloc] init]; 
message.from = @"JSON beast"; 
message.date = @"2012"; 
message.message = @"This is the best method available so far"; 

NSLog(@"%@", [person toJSONString]); 
+1

ありがとう!このライブラリは非常に便利です。 – BlackMamba

2

注:これはシリアル化可能なオブジェクトでのみ機能します。この回答は、ここで

- (NSString*) convertObjectToJson:(NSObject*) object 
{ 
    NSError *writeError = nil; 

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&writeError]; 
    NSString *result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

    return result; 
} 
+0

こんにちは。どのようにNSObjectの配列を変換する。ありがとうございました:) – kemdo

+0

ちょっと@kemdo - わからない - と私はもはやios devをやっていないので、本当に言うことができない....幸運! –

0

は私が助けることができる私のプロジェクトBWJSONMatcher、で使用されるライブラリです;-)質問自体に編集して上方に設けられたが、私はいつも「答え」セクションで回答のために自分を見ました。 jsonの文字列をデータ・モデルと簡単に一致させることができます。

... 
NSString *jsonString = @"{your-json-string}"; 
YourValueObject *dataModel = [YourValueObject fromJSONString:jsonString]; 

NSDictionary *jsonObject = @{your-json-object}; 
YourValueObject *dataModel = [YourValueObject fromJSONObject:jsonObject]; 
... 
YourValueObject *dataModel = instance-of-your-value-object; 
NSString *jsonString = [dataModel toJSONString]; 
NSDictionary *jsonObject = [dataModel toJSONObject]; 
... 
関連する問題

 関連する問題