gpt4 book ai didi

java - 如何从这个 JSON 对象中获取艺术家姓名的值?

转载 作者:行者123 更新时间:2023-12-01 17:58:45 24 4
gpt4 key购买 nike

我有以下 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 对象。如果您发现任何问题,请告诉我,谢谢!

最佳答案

什么是artists.getJSONObject(4)?您的数组似乎只显示数组中的一个对象。

应该只是...

artists.getJSONObject(0).getString("name")

关于java - 如何从这个 JSON 对象中获取艺术家姓名的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com