如何在objective-c中将对象写入JSON

时间:2014-01-08 03:53:32

标签: objective-c json nsdata

您好我是iOS编程的新手,我想将一个对象写入JSON文件,这是我的代码:

我想要转换为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 个答案:

答案 0 :(得分:1)

你不能只是将一个任意对象传递给NSJSONSerialization的dataWithJSONObject:options:error:,你必须传递一个顶层的数组或字典,其中只包含字符串或NSNumbers,符合{{3 }}

所以要做到这一点,你需要改变你拥有的东西

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