I’m trying to parse data from yahoo finance using JSON. For some reason the app keeps crashing. It seems that the last line of code is causing the crash. When I comment that line out, no crash happens. Here’s what I have so far…. Any ideas?
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://query.yahooapis.com/v1/public/yql? q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)%0A%09%09&env =http%3A%2F%2Fdatatables.org%2Falltables.env&format=json"] //2
#import "JsonViewController.h"
@implementation JsonViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:@"query"]; //2
NSLog(@"query: %@", latestLoans); //3
NSDictionary* loan = [latestLoans objectAtIndex:0]; /////// Where crash happens //////
}
@end
This is the error message in the console
[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6a65420
2012-07-15 01:18:29.492 Json[1730:f803] * Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6a65420’
This is because your JSON is decoding to an NSDictionary instead of an NSArray. If I am seeing the yahoo response properly, you probably want to fetch
objectForKey:@"results"and thenobjectForKey:@"quote"on that:this is how the JSON at the url you posted is structured:
Of course, you will want to expand that into proper validation steps, but the key is to know what is actually inside that returned JSON (I looked at your URI, and there were no arrays anywhere).