Search code examples
javatwitch

Twitch API - reading url with json in Java


I want to get the streams that contains special tag (url: https://api.twitch.tv/kraken/search/streams?q=tag) and get stream's info, e.g. viewers, name, link to the stream. I tried very much, but none of the code I used worked. Can someone help me with this?

    try {
        String sURL = "https://api.twitch.tv/kraken/search/streams?q=starcraft";

        URL url = new URL(sURL);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject rootobj = root.getAsJsonObject();
        String id = rootobj.get("_id").getAsString();
        System.out.println(id);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

Solution

  •     try 
            {
                        String sURL = "https://api.twitch.tv/kraken/search/streams?q=starcraft";
    
                        URL url = new URL(sURL);
                        HttpURLConnection request = (HttpURLConnection)url.openConnection();
                        request.connect();
    
                        JsonParser jp = new JsonParser();
                        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
                        JsonArray streams = root.getAsJsonObject().get("streams").getAsJsonArray();
                        for (JsonElement stream : streams)
                        {
                            System.out.println(stream.getAsJsonObject().get("_id"));
                            JsonElement channel = stream.getAsJsonObject().get("channel");
                            System.out.println(channel.getAsJsonObject().get("display_name"));
                            System.out.println(channel.getAsJsonObject().get("url"));
                        }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    

    The problem is that you try to get the _id from the root of your JSON result, but the structure has a streams member which contains all the streams.

    HTH Sal