5

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?

4

2 回答 2

16

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);
于 2012-07-27T16:42:36.763 回答
1

It seems you must ensure that the directories in the path exist, otherwise your app will hang and consume 100% of your CPU when using + writeJSONObject:toStream:options:error:. The file itself will be created by the stream.

于 2016-07-06T11:11:37.210 回答