我有以下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
这是for循环,因为我需要获取所有歌曲,在这里我只发布了部分JSON对象。如果您发现任何问题,请告诉我,谢谢!
答案 0 :(得分:4)
什么是artists.getJSONObject(4)
?您的数组似乎只显示数组中的一个对象。
应该只是......
artists.getJSONObject(0).getString("name")