Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to successfully convert JSON data to Objective-C objects?

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

like image 479
user1493543 Avatar asked Jul 25 '26 23:07

user1493543


1 Answers

It seems that [json objectForKey:@"similartracks"] returns a NSDictionary, try something like this:
NSArray* songList = [[json objectForKey:@"similartracks"] objectForKey:@"track"]

like image 172
Michele Percich Avatar answered Jul 27 '26 13:07

Michele Percich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!