Search code examples
javajsonresultset

Convert from ResultSet to JSON Object


I am trying to convert ResultSet to JSON object. I managed to get a JSON Array object already. Is there a way I can convert JSON object to JSON Array, or from ResultSet to JSON Object directly?

I tried to follow below suggestions in below link. How can I turn a JSONArray into a JSONObject?

But the JSON object I get now is like this:

{"data":[{"patient_key":80},{"eng_surname":"CAN"},{"eng_givename":"NOT"}....]}

I wish to have something like this for API calls:

{       "patientKey": 88,
        "hkid": " U0500574",
        "engSurname": "CAN",
        "engGivename": "NOT ", ....}

Is there any way I can get my desired result?

This is how I converted to JSON Array.

public static JSONArray convertToJSONArray(ResultSet resultSet)
            throws Exception {
        JSONArray jsonArray = new JSONArray();
        while (resultSet.next()) {
            int total_rows = resultSet.getMetaData().getColumnCount();
            for (int i = 0; i < total_rows; i++) {
                JSONObject obj = new JSONObject();
                obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
                        .toLowerCase(), resultSet.getObject(i + 1));
                jsonArray.put(obj);
            }
        }
        return jsonArray;
    }

Solution

  • I just managed two lines of your function in the question. Please tell me if it works. then i can tell you what was the problem!

        public static JSONArray convertToJSONArray(ResultSet resultSet)
                throws Exception {
            JSONArray jsonArray = new JSONArray();
            while (resultSet.next()) {
                JSONObject obj = new JSONObject();
                int total_rows = resultSet.getMetaData().getColumnCount();
                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;
        }