Home > OS >  Filter Metadata vom Spotify API
Filter Metadata vom Spotify API

Time:10-12

So, I'm getting track and album details from the Spotify API. Now I get a huge response. All I want is the artist, track, duration and if its explicit or not. How would I get duration_ms and explicit out of there? Thank you in advance:

Response looks approx like this:

{
"tracks": {
   "href":
   "items": [
      "album":{...}
      "artists":[..]
      "duration_ms": 125666,
      "explicit": false,

I have tried it with all kinds of variations now, but it doesn't work. Does it have to do with, that my needed metadata is inside an array and not Json body? This is where I'm at now:

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;
}

EDIT: Thanks you spencer I now did it like this: (I took the variables out of the loop to return them back)

//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");
    }

CodePudding user response:

You can use an org.json.JSONObject to parse that response.

        //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");
        }

Dependency if you're using Maven

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

Of course this is tailored to the get album tracks response at https://developer.spotify.com/documentation/web-api/reference/#endpoint-get-an-albums-tracks, but you can paste any of the sample responses in an online json formatter (like https://jsonformatter.curiousconcept.com/) so you can visualize the hierarchy better.

  • Related