Search code examples
iosjsonobjective-c

Error parsing Echo Nest API JSON with Objective-C


I am relatively new to Objective-C, but I have parsed JSON before with JavaScript.

I have this code in my viewDidLoad

NSURL *songsURL = [NSURL URLWithString:@"http://developer.echonest.com/api/v4/song/search?api_key=UVHRIOB9ISTKAAQ0R&format=json&results=1&combined=everybody%20dance%20now&bucket=id:7digital-UK&bucket=tracks&limit=true"];

NSData *jsonData = [NSData dataWithContentsOfURL:songsURL];

NSError *error = nil;

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

NSDictionary *item = [dataDictionary objectForKey:@"response"];
NSLog(@"%@", item);
NSDictionary *songs = [item objectForKey:@"songs"];
NSLog(@"%@", songs);
NSDictionary *songTitle = [songs objectForKey:@"title"];
NSLog(@"Title= %@", songTitle);

and it all works, until I try and fetch the song titles.

After I fetch the songs, the JSON looks like this:

(
    {
    "artist_foreign_ids" =         (
                    {
            catalog = "7digital-UK";
            "foreign_id" = "7digital-UK:artist:2060042";
        }
    );
    "artist_id" = ARKSHFP12D5CD74F5D;
    "artist_name" = "Everybody Left";
    id = SOWGJIF143A016B701;
    title = "We Are Everybody Left";
    tracks =         (
                    {
            catalog = "7digital-UK";
            "foreign_id" = "7digital-UK:track:32612792";
            "foreign_release_id" = "7digital-UK:release:3062491";
            id = TRZNPMZ1429AA0B7CE;
            "preview_url" = "http://previews.7digital.com/clip/32612792";
            "release_image" = "http://artwork-    cdn.7static.com/static/img/sleeveart/00/030/624/0003062491_200.jpg";
        }
    );
 }
)

I've tried getting other values, such as tracks using NSDictionary *tracks = [songs objectForKey:@"tracks"];, but I still get an error saying:

2014-08-29 01:54:07.612 khord[9530:60b] -[__NSCFArray objectForKey:]: unrecognized selector sent to     instance 0x987c450
2014-08-29 01:54:07.614 khord[9530:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x987c450'

Could anyone please offer me a solution on how I should parse this JSON correctly. I have a feeling that I'm not correctly understanding the data types.


Solution

  • songs is an array of dictionaries, each of which has a tracks key.

    Try:

    [[songs objectAtIndex:0] valueForKey:@"tracks"]