Reputation: 375
So the jist of what I'm doing is simple, getting some data from a server in JSON format. I'm using the default classes in Objective-C (specifically NSJSONSerialization) to convert the responseData gotten into JSON format.
So basically-
NSString* testURL=@"http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=Kendrick+Lamar&track=A.D.H.D&api_key=e3f53f2f2896b44ff158a586b8ee15c7&format=json";
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:testURL]];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* songList = [json objectForKey:@"similartracks"];
Problem is, later when I try to access an indivdual object in the array of JSOn data, like so,
NSDictionary* song1 = [songList objectAtIndex:0];
It's giving me this error,
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x96e2b60'
Any ideas as to why this is happening?
I appreciate the help, coffeejay
Upvotes: 3
Views: 3830
Reputation:
Your error message says that songList is a dictionary and not an array. Check the data structure.
Upvotes: 0
Reputation: 1548
When dealing with such things, you should always validate your response before trying to do something with it, you should never trust any input. In your case, you're trying to send objectAtIndex:
message to an NSDictionary
instance, which raises unrecognised selector exception.
A simple way to avoid such crashes is to check the class of the returned object, for instance:
id song1 = json[@"similartracks"]
if([song1 isKindOfClass:[NSArray class]])
{
//Now we're sure it's an array
}
Upvotes: 3
Reputation: 4520
Your json probably doesn't return an array at yhat point but a dictionary. Show the json content so we can help further.
(NsJSonSerialization returns id and can be either an array or dictionary. The contents again will be arrays or dictionaries)
Upvotes: 0
Reputation: 1892
It seems that [json objectForKey:@"similartracks"]
returns a NSDictionary, try something like this:
NSArray* songList = [[json objectForKey:@"similartracks"] objectForKey:@"track"]
Upvotes: 4
Reputation: 150605
You're declaring the returned data to be data
, but you are passing NSJSONSerialization
method a variable called responseData
.
Upvotes: 0