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

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

Constructing an interactive table from a JSON dataset using Node.js and Express

Just starting out with Node.JS here! I'm currently working on creating a page with multiple tables and information using NodeJS. However, I've hit a roadblock when trying to display the result of an SQL query in an HTML table. Right now, I'm ...

The typography text exceeds the boundaries of the Material-UI CardContent

In the React Material-UI framework, I am working with a CardContent component that looks like this: <CardContent className={classes.cardContent}> <Typography component="p" className={classes.title} variant="title"> {this.props.post.title ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...

Upon loading the page, include a class to a specific element within an AngularJS ng-repeat function by evaluating the content of a JSON object

I have a group of buttons that are generated from a json object. Whenever a user clicks on a button, it changes color (referred to as the selected color) using the ng-class directive with bootstrap classes. If the same button is clicked again, it reverts b ...

Challenges with Webpack sourcemaps

As I delve into learning nodejs and react, my current challenge lies in building bundle.js and debugging it within the browser. However, despite creating the bundle.map file, I am faced with errors as the webpack tab fails to appear in the browser. DevTool ...

Modify the directive when the scope variable undergoes changes

Utilizing an http request, I am retrieving data from a json file that I then utilize in my controller. app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) { //Getting data from the s ...

Issue with passing reactive property to component in Vue 3 application

I am currently working on a Vue 3 application and I am in the process of setting up a store for state management. Within this application, I have several important files that play different roles: app.vue component.vue main.js store.js These files contai ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Issue with code execution error in Pycharm when running Python

I am currently using Pycharm Professional version 2019.03 for running a Python code that streams Twitter data. Unfortunately, the code execution fails with the following error message: Traceback (most recent call last): File "C:/Users/HP/PycharmProje ...

Creating a line graph using chart.js and JSON dataset

I'm working on plotting a line graph using a JSON response from my MongoDB, but I keep encountering an error that indicates something might be wrong with my code structure. Here's what I have attempted: myurl = "/api/humidity" $(function() { ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

Python was unable to decode any JSON object

Attempting to extract information from a website. I have successfully inputted 'text' and 'longest_only' parameters, but when including the 'ontologies' parameter, it returns an error stating No JSON object could be decoded. H ...

Double Serialization with Java's Jackson Library

In my code, I have a class that includes a String field and a Map field. My goal is to serialize this class into JSON using Jackson. public class Mapping private String mAttribute; @JsonIgnore private Map<String, String> mMap; @J ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Linking information stored in an array to an object through the use of an intermediary object

How can we establish a connection between queued_Dr and upcoming_appointments using all_appointments? What would be the most effective solution for this issue? var queued_Dr = ["Dr.Salazar",["Dr.Connors","Dr.Johnson"],"D ...

Transmitting End of Transmission through Remote Socket

Iā€™m currently working on processing data in R received from a TCP Server Socket using JSON formatting. My script successfully establishes a connection with the server using: socketConnection(host = "whateverhost", port = "8080", server = FALSE, encodi ...

Is it possible to refresh the chat-box using PHP?

I recently created a chat box application using PHP, but I'm facing an issue with its automatic reload functionality. Is there a way to implement auto-reload in PHP itself, or would it be better to restructure the system to utilize AJAX? Additionally, ...

Can you recommend a basic, invertible, non-secure string cipher function that performs exceptionally well in terms of data dispersal?

I am in need of creating two functions to obscure and reveal a string, following the structure below: string encrypt(string originalText, string key) string decrypt(string scrambledText, string key) I require these functions to be concise and easy t ...