Sunday, May 12, 2013

NSJSONSerialization JSONObjectWithStream example ios

JSONObjectWithStream: options: error:

Returns a Foundation object from JSON data in a given stream.
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opterror:(NSError **)error
A stream from which to read JSON data.
The stream should be opened and configured.
opt( NSJSONSerialization JSONObjectWithStream example )
Options for reading the JSON data and creating the Foundation objects.
For possible values, see “NSJSONReadingOptions.”
If an error occurs, upon return contains an NSError object that describes the problem.
Return Value
A Foundation object from the JSON data in stream.
Discussion( NSJSONSerialization JSONObjectWithStream example )
The data in the stream must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
( NSJSONSerialization JSONObjectWithStream example )
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);
( NSJSONSerialization JSONObjectWithStream example )
NSString *json_list = [[NSBundle mainBundle] pathForResource:@"mylist" ofType:@"json"];
NSData *theList   =   [NSData dataWithContentsOfFile: json_list];
NSInputStream *listStream = [[NSInputStream alloc] initWithData:theList];
[listStream open];

if (showStream) {
    NSError *parseError = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithStream:listStream options:NSJSONReadingAllowFragments error:&parseError];        
    if ([jsonObject respondsToSelector:@selector(objectForKey:)]) {
        for (NSDictionary *firstItem in [jsonObject objectForKey:@"list"]) {
            NSLog(@"Title: %@", [firstItem objectForKey:@"title"]);
} else {
    NSLog(@"Failed to open stream.");