Twitch API - 用Java中的json读取url

时间:2016-07-17 20:40:52

标签: java twitch

我想获取包含特殊标记的流(网址:https://api.twitch.tv/kraken/search/streams?q=tag)并获取流信息,例如观众,名称,链接到流。我尝试了很多,但我使用的代码都没有。有人可以帮我这个吗?

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

1 个答案:

答案 0 :(得分:0)

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

问题是你试图从你的JSON结果的根目录获取_id,但结构有一个包含所有流的流成员。

HTH 萨尔