我正在使用Last.FM音频调音员来查找用户当前正在播放的歌曲:
key]&limit=1&format=json
但是,我在格式化方面遇到了问题。如果用户当前正在播放歌曲,则结果的格式如下:
"recenttracks": {
"track": [{
"artist": {
"#text": "Bruno Mars",
"mbid": "afb680f2-b6eb-4cd7-a70b-a63b25c763d5"
},
"name": "Just the Way You Are",
"streamable": "0",
"mbid": "39efbdb3-e2f2-4d9f-9f96-53ef364b2d72",
"album": {
"#text": "Doo-Wops & Hooligans",
"mbid": "33030768-eed0-404a-bd5e-af6950546211"
},
"url": "http:\/\/www.last.fm\/music\/Bruno+Mars\/_\/Just+the+Way+You+Are",
"image": [{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/34s\/98054239.png",
"size": "small"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/64s\/98054239.png",
"size": "medium"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/126\/98054239.png",
"size": "large"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/300x300\/98054239.png",
"size": "extralarge"
}],
"@attr": {
"nowplaying": "true"
}
}],
}我可以用json["recenttracks"]["track"][0]["name"].ToString()访问当前的歌曲
但是,如果用户当前没有播放歌曲,API将返回他们最后播放的歌曲.格式如下:
"recenttracks": {
"track": {
"artist": {
"#text": "Bruno Mars",
"mbid": "afb680f2-b6eb-4cd7-a70b-a63b25c763d5"
},
"name": "Just the Way You Are",
"streamable": "0",
"mbid": "39efbdb3-e2f2-4d9f-9f96-53ef364b2d72",
"album": {
"#text": "Doo-Wops & Hooligans",
"mbid": "33030768-eed0-404a-bd5e-af6950546211"
},
"url": "http:\/\/www.last.fm\/music\/Bruno+Mars\/_\/Just+the+Way+You+Are",
"image": [{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/34s\/98054239.png",
"size": "small"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/64s\/98054239.png",
"size": "medium"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/126\/98054239.png",
"size": "large"
}, {
"#text": "http:\/\/userserve-ak.last.fm\/serve\/300x300\/98054239.png",
"size": "extralarge"
}],
"date": {
"#text": "25 Jan 2015, 02:21",
"uts": "1422152473"
}
}
}您会注意到有一个轻微的格式变化。它不是以简单数组"track": [{}]的形式返回的,而是作为"track": {}返回的。
这意味着,为了访问歌曲的名称,我需要从前面提到的代码中删除[0]。
有什么方法我可以编程检查,以确定我需要使用哪种类型的代码来检索歌曲名称?我试过if (json["recenttracks"]["track"][0] != null)和if (json["recenttracks"]["track"].length > 0),但两者都不起作用。
发布于 2015-01-25 02:44:22
您应该能够检查json["recenttracks"]["track"]的类型
string name;
if(json["recenttracks"]["track"] is JArray)
{
name = json["recenttracks"]["tracks"][0]["name"].ToString();
}
else
{
name = json["recenttracks"]["tracks"]["name"].ToString();
}https://stackoverflow.com/questions/28132645
复制相似问题