JSON 来自 Wikipedia API with GSON - 解析具有不同名称的对象

JSON from Wikipedia API with GSON - Parse object with varying name

{
"batchcomplete": "",
"continue": {
    "grncontinue": "0.262157292819|0.262157407383|17998004|0",
    "continue": "grncontinue||"
},
"query": {
    "pages": {
        "29839198": {
            "pageid": 29839198,
            "ns": 0,
            "title": "Paradox (film)",
            "extract": "Paradox is a 2010 science-fiction television film starring Kevin Sorbo, Steph Song and Christopher Judge, directed by Brenton Spencer, and based on a three-part graphic novel mini-series by Christos Gage.\n\n"
        }
    }
}

我正在尝试找到一个解决方案来解析上述 JSON 来自 Wikipedia API 的结果。 问题是,由于“29839198”对象(在本例中)会因每次 API 调用而异,我似乎无法找到解析它的解决方案。

这是我目前拥有的:

URL url = new URL("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&generator=random&grnnamespace=0");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();

JsonElement jsonElement = new JsonParser().parse(new InputStreamReader((InputStream) request.getContent()));
JsonElement page = jsonElement.getAsJsonObject().get("?????");

通常我会关掉“????”对象名称的一部分。

使用 entrySet 获取 JsonElement:

        URL url = new URL("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&generator=random&grnnamespace=0");
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        JsonElement jsonElement = new JsonParser().parse(new InputStreamReader((InputStream) request.getContent()));
        JsonElement pages = jsonElement.getAsJsonObject().get("query").getAsJsonObject().get("pages");

        Set<Entry<String, JsonElement>> entrySet = pages.getAsJsonObject().entrySet();

        JsonElement yourDesiredElement = null;

        for(Map.Entry<String,JsonElement> entry : entrySet){
            yourDesiredElement = entry.getValue();
        }

        //null check for yourDesiredElement

希望对您有所帮助。