NSJSONReadingOptions - NSJSONReadingMutableLeaves
Options used when creating Foundation objects from JSON data—see
JSONObjectWithData: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 NSJSONReadingMutableLeaves example )
NSError *myError = nil; NSArray *jsonObjects= [NSJSONSerialization JSONObjectWithData:responseData ptions:NSJSONReadingMutableLeaves error:&myError]; for (NSDictionary * dict in jsonObjects) { NSLog(@"Some data %@", [dict objectForKey:@"field"]); //replace this to access a valid field }
( NSJSONSerialization NSJSONReadingMutableLeaves example )
NSError *myError = nil; NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError]; if (!res) { // JSON parser failed } // dictionary (top-level) if (![res isKindOfClass:[NSDictionary class]]) { // JSON parser hasn't returned a dictionary } // sethostname (array of dictionaries) NSArray *setHostNames = [res objectForKey:@"sethostname"]; // dictionary (array element) for (NSDictionary *setHostName in setHostNames) { // status (number) NSNumber *status = [setHostName objectForKey:@"status"]; // statusmsg (string) NSString *statusmsg = [setHostName objectForKey:@"statusmsg"]; … }
( NSJSONSerialization NSJSONReadingMutableLeaves example )
NSError *error = nil; NSURL *request = [NSURL URLWithString:query]; NSLog(@"Outgoing Request: %@",[request description]); NSString *response = [NSString stringWithContentsOfURL:request encoding:NSUTF8StringEncoding error:nil]; if (error) { NSLog(@"ERROR: Unable to get response %@",[error localizedDescription]); } NSLog("@Synchronous Response: %@",response); NSData *jsonData = [response dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error]; if (error) { NSLog(@"ERROR: Unable to parse JSON %@",[error localizedDescription]); }