Fergy323
Fergy323

Reputation: 33

Confusion with obtaining a value from a JSON string using GSON

so I've had the idea to try and make a program which can obtain subscriber counts through Google APIs, however my lack of knowledge in JSON has become my downfall.

    public static void main(String[] args) throws IOException {

    String url = "https://www.googleapis.com/youtube/v3/channels? 
    part=statistics&key=sWDdmcweForstackoverflowDW&forUsername=damonandjo";
    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new 
    InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println(response.toString());
}

This will print information such as this to the console. https://pastebin.com/jqTCJTtR

My question is how would I go about parsing this, and what is the easiest way to do it with it out running it through other classes etc? I have tried multiple different libraries and a lot seem to be outwith the bounds of what I am trying to achieve. Thank you very much to anyone willing to help.

EDIT: So with the help of Not a JD I have been able to make some progress with this, however I believe the map is iterating over the actual arrays and not their contents which is what I want to access. If anyone can help me do this Ibwould be very grateful

Upvotes: 0

Views: 57

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38645

You can always deserialise every JSON to Map of key value pairs or List of Map-s. It depends from your root object in JSON. In your case you have JSON object so we can deserialise it to Map. Knowing that we can deserialise given JSON and find subscriberCount as below:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();
        FileReader json = new FileReader(jsonFile);

        Gson gson = new GsonBuilder().create();

        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> response = gson.fromJson(json, type);

        Optional<Integer> subscriberCount = getSubscriberCount(response);
        if (subscriberCount.isPresent()) {
            System.out.println(subscriberCount.get());
        }
    }

    public static Optional<Integer> getSubscriberCount(Map<String, Object> response) {
        Object items = response.get("items");
        if (items instanceof List) {
            Object item0 = ((List) items).get(0);
            if (item0 instanceof Map) {
                Object statistics = ((Map) item0).get("statistics");
                if (statistics instanceof Map) {
                    Object subscriberCount = ((Map) statistics).get("subscriberCount");
                    return Optional.of(Integer.parseInt(subscriberCount.toString()));
                }
            }
        }

        return Optional.empty();
    }
}

In case your items element can more element you need to iterate over it. Also check whether items is not empty. Example shows hot to get 0-element from it.

Upvotes: 0

Not a JD
Not a JD

Reputation: 1902

Quick and easy might be to use gson:

    Gson gson = new Gson(); 
    Map<String,Object> map = (Map<String,Object>) gson.fromJson(jsonString, Map.class);

Take a look at the keys in the map.

E.g. map.get(resultsPerPage) will return 5.

Upvotes: 1

Related Questions