GSON - Decoding JSON Obtained through Wikipedia API with Dynamic Object Naming

{
"batchcomplete": "uniqueText123",
"continue": {
    "grncontinue": "0.262157292819|0.262157407383|17998004|0",
    "continue": "grncontinue||"
},
"query": {
    "pages": {
        "54321098": {
            "pageid": 54321098,
            "ns": 1,
            "title": "Incredible (movie)",
            "extract": "Incredible is a 2022 action-packed film starring Tom Cruise, Emma Stone and Chris Evans, directed by John Lee Hancock, and based on an original screenplay by Paul Anderson.\n\n"
        }
    }
}

I'm attempting to discover a resolution for interpreting the previously mentioned JSON outcome from the Wikipedia API. The challenge lies in the fact that since the "54321098" object (in this instance) will differ with each API request, I'm struggling to come up with a solution for interpretation.

This is my current progress:

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

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

Usually, I would substitute the "????" part with the object name.

Answer №1

Here is a way to obtain the JsonElement using entrySet:

        URL link = new URL("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&generator=random&grnnamespace=0");
        HttpURLConnection request = (HttpURLConnection) link.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>> elementSet = pages.getAsJsonObject().entrySet();

        JsonElement desiredElement = null;

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

        //Ensure yourDesiredElement is not null

This solution should be helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rails failing to properly decode JSON from jQuery resulting in an array transforming into a hash with integer keys

Every time I try to send an array of JSON objects from jQuery to Rails using a POST request, I encounter the same issue. When I stringify the array, it seems that jQuery is handling it correctly: "shared_items"=>"[{\"entity_id\":\"253&bs ...

Laravel integration with JsGrid

I'm relatively new to JsGrid and I'm attempting to implement certain functionalities similar to the one demonstrated at this link in a Laravel project. However, I encountered an error stating "Undefined index: id". I'm trying to retrieve dat ...

Converting a Map to Json in Play Scala: A Step-by-Step Guide

Is there a way to convert the given Map structure, which is of type Map[String,Any], into JSON in Scala using Play framework? val result = s .groupBy(_.dashboardId) .map( each => Map( "dashboardId" -> each._1, "cubeId" -> ...

Utilizing Selenium WebDriver for Automated Testing of Dropdown Menus

When it comes to selecting an option from a dropdown box, there are multiple approaches that can be taken. I have previously used the following method: driver.findElement(By.id("selection")).sendKeys("Germany"); However, this method did not always guaran ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Creating a JSON object by utilizing database relationships and foreign keys in PHP

Seeking assistance with a task. The task involves establishing a simple mapping relation (FK) between two databases and then converting this data into JSON format using PHP. Consider the following abstract database structures: 1: Customer +-------+---- ...

What could be causing the java.lang.NullPointerException to occur in my code?

I am encountering a java.lang.NullPointerException error when trying to execute objUserName.sendKeys(uname); @FindBy(how=How.XPATH,using="//input[@placeholder='Username']") static WebElement objUserName; public LoginFeature(){ PageFactory.i ...

sending a POST request with multiple parts using d3.json() or d3.xhr()

Currently, there seems to be a lack of support for submitting multipart form data with a request. While I understand how to perform a POST with d3.json().post() as outlined in this resource, I am specifically interested in using POST to submit parameters t ...

Understanding JSON Dates

At this point, I find myself a bit puzzled with what I'm currently observing. To elaborate, the scenario involves me converting a MongoDate to JSON by utilizing PHP's json_encode function along with MongoDB functionalities. The resulting output c ...

Combining JSON data within a MySQL column efficiently with the power of SQLAlchemy

Is there a way to consolidate JSON data that is spread out over multiple rows in a MySQL column using the Python SQLAlchemy library? I tried using json_merge_preserve but encountered difficulties applying it to an entire column. This was the code snippet ...

What is the proper way to send a HTTP status code 409 (conflict) and a JSON response from a spring REST API when a duplicate email is detected while a user is registering

I have attempted a few solutions so far, including: Using the Response object, but I prefer to avoid utilizing the servlet API of JSP. Trying a solution that returns an HTML response with a status code, however, I need it to be JSON instead. Here is a ...

Tips for displaying a populated ViewBag string from a try/catch block on the screen

I'm currently working on parsing a JSON file in my controller and implementing try/catch functionality for any errors that may arise. When an error occurs during the JSON parsing process, I populate ViewBag with the error message and attempt to displa ...

Leveraging WebDriver Extensions for uploading files via the Grid

Hey there, I'm currently trying to utilize WebDriver extensions for selenium. Unfortunately, I've hit a roadblock when it comes to uploading a file. Locally, I can upload the file using robot by doing something like this: robot.keyPress(KeyEvent. ...

"Step-by-step guide on setting up Selenium with Java on a fresh system and implementing Jenkins as a continuous integration (CI) tool for

Embarking on Automation in my current project, I am looking to implement Selenium for Test Automation using Java. With Jenkins (formerly known as Hudson), I aim to generate accurate Test Reports. Could you guide me through the installation and configuratio ...

Agreement between parse.com and the mobile application

What is the communication protocol used between the parse.com backend and mobile app when utilizing the Android/IOS SDK? In the given code snippet, how is a ParseObject returned - is it transmitted over http as json (Rest), via socket, rpc, or any other m ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Errors in JSON.parse: which character am I not detecting?

My development environment includes PHP 5.3.5, MySQL Server 5.5.8, and jquery version 1.6. I'm using Ajax to automatically populate a dropdown list of countries, but I keep encountering an error that persists despite trying various solutions. For exa ...

Personalize the JSON formatting in a Django Rest Framework GET request

I'm having an issue with retrieving a filtered list from my MySQL database. The query seems correct, but the JSON output is not as expected: [ { "id": "0038", "name": "Jane Doe", "total_hrs_pe ...

Discover the effective approach for executing JMeter to effortlessly display the absent elements

I have two separate GET APIs that return response codes containing an ID number and a corresponding title. For API_1, here are some sample responses (with 100 IDs): { "result": "OK", "obj": { "list" : [ { "id" : 9 ...

The type '_InternalLinkedHashMap<String, dynamic>' is incompatible with the type 'BanarModel'

There seems to be an issue with the code. I believe it is because I stored an object in a list, so how can I solve this? The error message says '_InternalLinkedHashMap' is not a subtype of type 'BanarModel'. class Home ...