-1

I have a ResultSet object as a result of request to a table:

ResultSet result = stat.executeQuery("SELECT * FROM Greetings");

I need to return it to browser in json format. Is it possible to use some Restlet tool to convert the variable of ResultSet type to json object and send it to web client?

vitaliy4us
  • 483
  • 5
  • 21
  • 1
    Maybe I'm confused, but there are so many questions on this site that deal with ResultSet to JSON conversion, including those found in [this link](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+resultset+to+json). – Hovercraft Full Of Eels Nov 13 '16 at 15:48

2 Answers2

2

You can use following function to convert resultSet into jsonArray and send it to your browser.

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

private JSONArray convertToJSON(ResultSet resultSet)
        throws Exception {
    JSONArray jsonArray = new JSONArray();

    while (resultSet.next()) {
        int total_rows = resultSet.getMetaData().getColumnCount();
        JSONObject obj = new JSONObject();
        for (int i = 0; i < total_rows; i++) {
            obj.put(resultSet.getMetaData().getColumnLabel(i+1)
                    .toLowerCase(), resultSet.getObject(i + 1));
        }
        jsonArray.put(obj);
    }

    return jsonArray;
}
Suresh A
  • 1,178
  • 2
  • 10
  • 21
  • Please let me ask if this answer is not sufficient . I will update my answer according to your requirement . – Suresh A Nov 13 '16 at 16:04
0

You can use /jackson/databind/ObjectMapper class to convert Java object to JSON.

  ObjectMapper mapper = new ObjectMapper();

  Greetings greetings = new Greetings();

  //Object to JSON in file
  mapper.writeValue(new File("c:\\file.json"), greetings);

  //Object to JSON in String
  String jsonInString = mapper.writeValueAsString(greetings);

Maven POM dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
sahoora
  • 245
  • 1
  • 5