如何从此JSON对象获取艺术家姓名的值?
问题描述:
我有以下JSON对象(抱歉的长度),我需要获取艺术家的名字。它应该在曲目 - >项目 - >专辑 - >艺术家 - >名称下。我正在尝试运行此代码,但我无法获取艺术家的姓名。这里是JSON对象的一部分:如何从此JSON对象获取艺术家姓名的值?
{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=closer&type=track&offset=0&limit=20",
"items" : [ {
"album" : {
"album_type" : "single",
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/69GGBxA162lTqCwzJG5jLp"
},
"href" : "https://api.spotify.com/v1/artists/69GGBxA162lTqCwzJG5jLp",
"id" : "69GGBxA162lTqCwzJG5jLp",
"name" : "The Chainsmokers",
"type" : "artist",
"uri" : "spotify:artist:69GGBxA162lTqCwzJG5jLp"
} ],
"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],
.....
我需要得到它说:"name" : "The Chainsmokers",
行了,但我不能弄明白。这是我到目前为止有:
JSONObject jObj;
JSONObject tracks;
JSONArray items;
JSONObject album;
JSONArray artists;
JSONObject aName;
jObj = new JSONObject(json);
tracks = (JSONObject) jObj.get("tracks");
items = (JSONArray) tracks.get("items");
String songName;
Log.d("searchSong", json);
// Return all of the results for the searched song. This will return to a ListView with the song name, uri, and artist name.
for (int i = 0; i < items.length(); i++) {
try {
songName = items.getJSONObject(i).getString("name");
if (!(songName.toLowerCase().contains(query.toLowerCase()))) {
continue;
}
// TODO THIS DOESN'T WORK!!!!
// How do I get artistname????
album = (JSONObject) items.getJSONObject(i).get("album");
artists = album.getJSONArray("artists"); // get the artist name
String artistsName = artists.getJSONObject(4).toString();
String artistName = "";
artistName = artists.getJSONObject(i).getString("name");
// This stuff works
id = items.getJSONObject(i).getString("id");
lViewSearch.setVisibility(View.VISIBLE);
lView.setVisibility(View.INVISIBLE);
bNext.setVisibility(View.INVISIBLE);
bPlay.setVisibility(View.INVISIBLE);
searchSongs.add(songName + "\n" + id);
searchAdapter.notifyDataSetChanged();
svSong.clearFocus();
} catch (JSONException e) {
e.printStackTrace();
}
} // end for loop
这是一个循环,因为我需要让所有的歌曲,在这里我只张贴的JSON对象的一部分。如果您看到任何问题,请告知我,谢谢!
答
什么是artists.getJSONObject(4)
?你的数组似乎只显示数组中的一个对象。
应该只是......
artists.getJSONObject(0).getString("name")
是否引发任何错误?你取而代之的是什么?看起来像一个标准的调试问题。放置一个断点将有助于你。此外,'String artistsName = artists.getJSONObject(4).toString();',你可能想尝试索引3。只是一个预感。 – Sid
您是否找不到适用于Spotify的Java API? –
我一直在处理这个很长一段时间,它还没有完成,甚至没有通过spotify制作,所以很难为我工作 – Michael