Twitch API - 在 Java 中用 json 阅读 url

Twitch API - reading url with json in Java

我想获取包含特殊标签 (url: https://api.twitch.tv/kraken/search/streams?q=tag) 的流并获取流的信息,例如viewers, name, link 添加到流中。我尝试了很多次,但我使用的 none 代码有效。有人可以帮我解决这个问题吗?

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