0

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

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Ben. Thanks for your quick reply. it totally makes sense to me. But Where can I file this file? It isn't in the project navigation bar.
I found the solution for checking the content of the created file. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.