Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing JSON data to disk

What is the easiest way to write a JSON data/NSDictionary and read it back again? I know there's NSFileManager, but is there an open source framework library out there that would make this process easier? Does iOS5 NSJSONSerialization class supports writing the data to disk?

like image 892
adit Avatar asked Jul 27 '12 16:07

adit


1 Answers

Yup, NSJSONSerialization is the way to go:

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);
like image 118
Richard J. Ross III Avatar answered Sep 28 '22 10:09

Richard J. Ross III