【问题标题】:Filter Metadata vom Spotify API过滤元数据 vom Spotify API
【发布时间】: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


    【解决方案1】:

    您可以使用 org.json.JSONObject 来解析该响应。

            //GET https://api.spotify.com/v1/albums/{id}/tracks
    
            String response_json = "..." //from webservice
    
            JSONObject json = new JSONObject(response_json);
            JSONArray items = json.getJSONArray("items");   
            for(int i = 0; i < items.length(); i++){
                JSONObject item = items.getJSONObject(i);
                long duration_ms = item.getLong("duration_ms");
                boolean explicit = item.getBoolean("explicit");
            }
    

    使用 Maven 时的依赖关系

       <dependency>
           <groupId>org.json</groupId>
           <artifactId>json</artifactId>
           <version>20180813</version>
           <type>jar</type>
       </dependency>
    

    当然,这是针对https://developer.spotify.com/documentation/web-api/reference/#endpoint-get-an-albums-tracks 获取专辑曲目响应量身定制的,但您可以将任何示例响应粘贴到在线 json 格式化程序(如https://jsonformatter.curiousconcept.com/)中,以便更好地可视化层次结构。

    【讨论】:

    • 谢谢jsonformatter真的很有帮助!我试图用邮递员来做。首先,我不确定我的元数据是在专辑中还是在项目中。
    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2014-07-28
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多