Writing JSON data to disk

What is the easiest way to write JSON / NSDictionary data and read it again? I know NSFileManager there, but is there an open source library that will simplify this process? Does iOS5 NSJSONSerialization class support writing data to disk?

+5
source share
2 answers

Yup NSJSONSerializationis the way:

NSString *fileName = @"myJsonDict.dat"; // probably somewhere in 'Documents'
NSDictionary *dict = @{ @"key" : @"value" };

NSOutputStream *os = [[NSOutputStream alloc] initToFileAtPath:fileName append:NO];

[os open];
[NSJSONSerialization writeJSONObject:dict toStream:os options:0 error:nil];
[os close];

// reading back in...
NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:fileName];

[is open];
NSDictionary *readDict = [NSJSONSerialization JSONObjectWithStream:is options:0 error:nil];
[is close];

NSLog(@"%@", readDict);
+15
source

It seems you should make sure that the directories in the path exist, otherwise your application will freeze and consume 100% of your processor when used + writeJSONObject:toStream:options:error:. The file itself will be created by the stream.

+1
source

All Articles