Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code:

    public String evaluate() throws Exception
{
    // Code block here
}

I need assistance in using GSON JSON utility methods to convert the result set to a JSON object. Any guidance would be appreciated!

Answer №1

json.org offers a user-friendly API for developers to utilize: http://json.org/java/

You can implement the following approach:

  • Go through each row in your dataset
  • For every column, generate a JSON object containing key/value pairs:

column = { "column1" : 123" }

  • Add each column object to an array associated with the row

row = [ { "column1" : 123" }, { "column2" : 456" } ]

  • Append each row to an array

rows = [ [ { "column1" : 123" }, { "column2" : 456" } ], [ { "column1" : 111" }, { "column2" : 222" } ]]

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

JSONArray rows = new JSONArray();
while(rs.next())
    {
        JSONArray columns = new JSONArray();
        for(int i = 0; i < columnNames.length; i++)
        {
            JSONObject jsonObj = new JSONObject(); 
            jsonObj.put(columnNames[i], rs.getString(i + 1));
            columns.put(jsonObj);
        }
        rows.put(columns);
    }
    rs.close();
return rows.toString();

Answer №2

After running into some issues, I found a solution that worked perfectly for me:

I decided to simplify the process by removing all XML and table building details from my code. Instead, I opted to directly convert the result set into a GSON JSON array and output the JSON data. Here's how I achieved this:

JsonArray reportArray = JsonUtilities.resultSetToJsonObjectArray(ep.execute()[0]); //Convert Result Set to JsonArray

    ResultSetMetaData rsmd = rs.getMetaData();
    String[] columnNames = new String[rsmd.getColumnCount()];
    for(int i = 0; i < columnNames.length; i++)
        columnNames[i] = rsmd.getColumnName(i + 1).toLowerCase();

    rs.close();
    ep.close();

    Gson gson =  new GsonBuilder().setPrettyPrinting().create();  //Create JSON object and format output for readability
    String JSONData = gson.toJson(reportArray);      
    return JSONData;

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

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

Develop an "Import Interface" using TypeScript

I have a large project with many files and I believe using an import object would be beneficial. For instance, consider having menu.ts at the top level that every program will refer to: import router from "./router/index"; import controllers from ...

I have successfully established a new channel, but I am having difficulty retrieving the unique identifier for it

After using the provided code to create a channel, I'm having trouble locating the channel ID needed for the next step in my function. This function is meant to move to a specific category and send a message to it. const buyid = generateID message. ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

Tips for preventing a function from being triggered twice during a state change

I'm currently working with a react component that looks like this: const [filter, setFilter] = useState(valueFromProps); const [value, setValue] = useState(valueFromProps); const initialRender = useRef(true); useEffect(() => { if (initialRender. ...

Accessing data points in jQuery

Here is a sample code I'm working with : <script type="text/javascript"> var currentPicture;//default picture var picEL;//the image viewer element jQuery("#backImageShower").hover( function(i) { picEL = j ...

Failure of AJAX to transmit variable to PHP script

I am relatively new to PHP and currently working on the dashboard page of a website where an administrator can view all existing admins. Each admin's row has a button that is supposed to check their privileges, such as access to article editing and cl ...

Guide on how to loop through a JSON request using a mule integration framework

First of all, I want to express my gratitude for the incredible work you are doing. I have been increasingly drawn to your website, and now I find myself in need of assistance for the first time. Currently, I am exploring mule esb and attempting to iterat ...

Enable a click event within an iFrame by clicking on an element in the parent document

I am attempting to trigger the click event of an element inside an iFrame (specifically a standard Twitter follow button) when clicking on an element within my main webpage. Below is the code snippet I have been experimenting with, but unfortunately it do ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

Is it possible to show a pop-up window containing aggregated data when the jQuery double-click event

How can I create a pop-up window to display aggregated data when the Double-click event is triggered in jQuery? In my code, each questionId has multiple related reasons. When a user clicks or selects a questionId button/event, the selected questionId will ...

The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality it ...

What is the best way to include a second (concealed) value in a cell using datatables

Query: How can I send specific cell values to a controller using POST method, where one value is visible and the other is hidden? For instance, each cell contains both Time and Date data but only the Time is displayed in the datatable. I need to post both ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

Using JavaScript's if-else statements is akin to a checkbox that is always in its

When working with checkboxes, I can retrieve the state (checked or unchecked) in the browser developer console using $("#blackbox").prop('checked')or $('#blackbox').is(':checked'). I have tried both methods. For example, if I ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure: // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; When a user inputs produ ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...