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();