I have a resultset as a result of a MySQL query using the JDBC connector. So my job is to convert the resultset into a JSON format. So that I can send it to the clientside a
I found best solution here.
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.ResultSet;
/**
* Convert a result set into a JSON Array
* @param resultSet
* @return a JSONArray
* @throws Exception
*/
public static JSONArray convertToJSON(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;
}