2014-01-08 81 views
0

嗨,我是新來的iOS編程,我想寫一個對象成JSON文件,這裏是我的代碼:如何對象寫入JSON在Objective-C

我是對象的

結構試圖轉換成JSON:

#import <Foundation/Foundation.h> 

@interface QuestionAnswerPair : NSObject 

@property(strong, nonatomic) NSString *question; 
@property(strong, nonatomic) NSString *answer; 


@end 

,試圖對象寫入JSON文件中的代碼:

QuestionAnswerPair qaPair = [[QuestionAnswerPair alloc] init ]; 
[qaPair setQuestion:QUESTION]; 
[qaPair setAnswer:@"It's salmon"]; 

NSError *jsonError = [[NSError alloc] init]; 
NSData *jsonFile = [NSJSONSerialization dataWithJSONObject:qaPair options:NSJSONWritingPrettyPrinted error:&jsonError]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.json"]; 

[jsonFile writeToFile:appFile atomically:NO]; 

回答

1

你不能僅僅通過一個任意對象爲NSJSONSerialization的dataWithJSONObject:選項:錯誤:,你有E要通過在頂層數組或字典,只有在他們裏面的字符串或NSNumbers,每個文檔在https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

所以做這項工作,你需要改變什麼,你必須

NSData *jsonFile = [NSJSONSerialization dataWithJSONObject: @[qaPair.question, qaPair.answer] options:NSJSONWritingPrettyPrinted error: &jsonError]; 
+0

嗨,本。感謝您的快速回復。這對我來說完全有意義。但我可以在哪裏存檔這個檔案?它不在項目導航欄中。 – mko

+0

我找到了檢查創建文件內容的解決方案。再次感謝 – mko