Sunday, May 12, 2013

NSJSONSerialization NSJSONReadingMutableContainers example ios


NSJSONReadingOptions - NSJSONReadingMutableContainers

Options used when creating Foundation objects from JSON data—seeJSONObjectWithData:options:error: and JSONObjectWithStream:options:error:.
enum {
   NSJSONReadingMutableContainers = (1UL << 0),
   NSJSONReadingMutableLeaves = (1UL << 1),
   NSJSONReadingAllowFragments = (1UL << 2)
};
typedef NSUInteger NSJSONReadingOptions;
Constants
NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
NSJSONReadingMutableLeaves
Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
NSJSONReadingAllowFragments
Specifies that the parser should allow top-level objects that are not an instance of NSArray orNSDictionary.


( NSJSONSerialization NSJSONReadingMutableContainers example )

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);
   }
}

( NSJSONSerialization NSJSONReadingMutableContainers example )
NSString *s = @"{ \"objs\": [ \"a\", \"b\" ] }";    
NSData *d = [NSData dataWithBytes:[s UTF8String] length:[s length]];
id dict = [NSJSONSerialization JSONObjectWithData:d options:NSJSONReadingMutableContainers error:NULL];

NSLog(@"%@", dict);

[[dict objectForKey:@"objs"] addObject:@"c"];

NSLog(@"%@", dict);
NSLog(@"%@", [[dict objectForKey:@"objs"] class]);
( NSJSONSerialization NSJSONReadingMutableContainers example )
NSData *dictData2 = [@"{ \"foo\": \"bar\" }" dataUsingEncoding:NSUTF8StringEncoding];
id dict2 = [NSJSONSerialization JSONObjectWithData:dictData2 options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@", [dict2 class]);
NSLog(@"%@", [dict2 superclass]);
NSLog(@"%d", [dict2 isKindOfClass:[NSMutableDictionary class]]);

// This works...
[dict2 setObject:@"quux" forKey:@"baz"];
NSLog(@"%@", dict2);

NSData *dictData = [@"{}" dataUsingEncoding:NSUTF8StringEncoding];
id emptyDict = [NSJSONSerialization JSONObjectWithData:dictData options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@", [emptyDict class]);
NSLog(@"%@", [emptyDict superclass]);
NSLog(@"%d", [emptyDict isKindOfClass:[NSMutableDictionary class]]);

//...but this fails:
[emptyDict setObject:@"quux" forKey:@"baz"];
NSLog(@"%@", emptyDict);