Skip to content

Instantly share code, notes, and snippets.

@casspangell
Created April 26, 2012 16:43
Show Gist options
  • Save casspangell/2500879 to your computer and use it in GitHub Desktop.
Save casspangell/2500879 to your computer and use it in GitHub Desktop.
JSON trial and error
- (void) getJSON {
// Create the request.
NSURLRequest *urlRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.zeroeightysix.com/Logovision/jsonhotspotting.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//Create queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// JSON as a NSData object
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[self parseJSONFromData:data];
}];
}
- (void)parseJSONFromData:(NSData *)data {
NSError* error;
//create array with data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", error);
}
//Parse the data into an array: thisArray[NSDictionary][NSArray]
[jsonArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
}];
//Creates a dictionary with jsonArray[0]
NSDictionary *fileInfo = [jsonArray objectAtIndex:0];
NSString *filename = [fileInfo objectForKey:@"filename"];
NSLog(@"%@", filename);//prints "jamesbond.mp4"
//Create an array with jsonArray[1]
NSArray *dataArray = [jsonArray objectAtIndex:1];
//Create a dictionary that contains n hotspot objects
NSDictionary *hotspotItem = [dataArray objectAtIndex:1];
NSArray *itemName = [hotspotItem objectForKey:@"hotspots"];
//Create dictionary from itemName[0] to access individual hotspot data item
NSDictionary *hotspotItemData = [itemName objectAtIndex:0];
NSLog(@"%@", [hotspotItemData objectForKey:@"height"]); //prints "144"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment