【发布时间】:2021-11-30 12:52:11
【问题描述】:
所以,我从 Spotify API 获取曲目和专辑详细信息。现在我得到了巨大的反响。 我想要的只是艺术家、曲目、持续时间以及是否明确。我如何从那里获得 duration_ms 和明确的?提前致谢:
响应大致如下:
{
"tracks": {
"href":
"items": [
"album":{...}
"artists":[..]
"duration_ms": 125666,
"explicit": false,
我现在已经尝试了各种变体,但它不起作用。它是否与我需要的元数据位于数组中而不是 Json 主体有关? 这就是我现在所处的位置:
public static String filterMetadata(String metadata) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(metadata);
JsonNode durationNode = rootNode.at("/tracks/items/duration_ms"); //Path must start with a slash! /
String duration = durationNode.asText();
return duration;
}
编辑:谢谢斯宾塞,我现在这样做了:(我将变量从循环中取出以将它们返回)
//Function to filter the response we got from Spotify back
public static String filterMetadata(String metadata) throws IOException {
JSONObject json = new JSONObject(metadata);
JSONObject tracks = json.getJSONObject("tracks");
JSONArray items = tracks.getJSONArray("items");
int duration_ms = 0;
boolean explicit = true;
for(int i = 0; i < items.length(); i++){
JSONObject item = items.getJSONObject(i);
duration_ms = item.getInt("duration_ms");
explicit = item.getBoolean("explicit");
}
【问题讨论】:
标签: java json spring spring-boot jackson