Search code examples
objective-cjsonnsdata

How to write an object into JSON in objective-c


Hi I'm new to iOS programming, I want to write an object into a JSON file, here's my code:

structure of the object that I'm trying to convert into json:

#import <Foundation/Foundation.h>

@interface QuestionAnswerPair : NSObject

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


@end

The code that trying to write an object into JSON file:

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];

Solution

  • You can't just pass an arbitrary object into NSJSONSerialization's dataWithJSONObject: options:error:, you have to pass in an array or dictionary at the top level, with only strings or NSNumbers inside them, per the documentation at https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

    so to make this work, you need to change what you have to

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