Reputation: 4652
I m trying to parse json returned by twitter. The json is retrieved well and i convert it to NSDictionary,
NSLog on dictionary object works well and shows all the tweets.
NSLog(@"Twitter response: %@", dict);
but getting following error when i try to get objectForKey for any key in dict object:
2012-02-07 15:35:28.988 TestTweetApp[1525:12103] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a2a370 [Switching to process 1525 thread 0x12103] [Switching to process 1525 thread 0x12103] 2012-02-07 15:35:28.997 TestTweetApp[1525:12103] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a2a370' * First throw call stack: (0x176e052 0x1a40d0a 0x176fced 0x16d4f00 0x16d4ce2 0x3044 0xd306 0x2048445 0x2049ecf 0x2049d28 0x20494af 0x9ca1fb24 0x9ca216fe) terminate called throwing an exceptionsharedlibrary apply-load-rules all
code for viewDidLoad() function is:
- (void)viewDidLoad
{
[super viewDidLoad];
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json?screen_name=[SOME_USER_NAME]&include_entities=true"] parameters:nil requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(@"Twitter response: %@", [dict objectForKey:@"entities"]);
}
else
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
Upvotes: 1
Views: 1110
Reputation: 171
If you are unsure about the response format or may have multiple possible response formats and if you also need to handle errors, you may use any of the introspection methods like isKindOfClass
or respondsToSelector
to determine the type returned by JSONObjectWithData
id responseData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if([responseData respondsToSelector:@selector(objectForKey:)]){
//Response is of type NSdictionary
NSLog(@"Twitter response: %@", [responseData objectForKey:@"entities"]);
}else if ([responseData respondsToSelector:@selector(objectAtIndex:)]){
//Response is of type NSArray
}
else{
// error
}
Upvotes: 2
Reputation: 8147
It seems that your response is a NSArray
instead of a NSDictionary
. Try
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error]);
before your
NSDictionary *dict...
line and see the format. Then move it to an NSArray and access the elements properly.
NSArray *response = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(@"elements = %@", response);
Upvotes: 2