使用GSON从JSON字符串获取值的困惑

时间:2019-03-17 03:07:26

标签: java json gson

所以我有一个想法,尝试创建一个可以通过Google API获取订阅者人数的程序,但是我对JSON的了解不足已成为我的失败。

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

这会将诸如此类的信息打印到控制台。 https://pastebin.com/jqTCJTtR

我的问题是我将如何解析它,而通过其他类等运行它最简单的方法是什么?我尝试了多种不同的库,但很多似乎超出了我要实现的范围。非常感谢任何愿意提供帮助的人。

编辑:因此,在非JD的帮助下,我已经能够取得一些进展,但是,我相信地图是在实际数组上而不是我要访问的内容上进行迭代。如果有人可以帮助我做到这一点,我将非常感激

2 个答案:

答案 0 :(得分:1)

快速简便可能是使用gson:

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

看看地图上的按键。

例如map.get(resultsPerPage)将返回5。

答案 1 :(得分:0)

您始终可以将键值对的每个JSONMapList -s的Map进行反序列化。它取决于JSON中的根对象。在您的情况下,您有JSON object,因此我们可以将其反序列化为Map。知道我们可以对给定的JSON进行反序列化并找到subscriberCount,如下所示:

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

如果您的items元素可以包含更多元素,则需要对其进行迭代。同时检查items是否不为空。示例显示了从中获取0-element的热情。