我对Objective-C比较陌生,但我之前用JavaScript解析过JSON。
我的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);
这一切都有效,直到我尝试获取歌曲标题。
获取歌曲后,JSON看起来像这样:
(
{
"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";
}
);
}
)
我尝试使用tracks
获取其他值,例如NSDictionary *tracks = [songs objectForKey:@"tracks"];
,但我仍然收到错误消息:
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'
有谁能请我解决一下如何正确解析这个JSON。我有一种感觉,我没有正确理解数据类型。
答案 0 :(得分:0)
歌曲是一系列词典,每个词典都有一个曲目键。
尝试:
[[songs objectAtIndex:0] valueForKey:@"tracks"]