Browse Category


[Java] Convert SQL ResultSet to JSON Array

JSON is a handy format while dealing with data in front end. However, the default return type of querying data via JDBC is ResultSet.

Fortunately, below is the method I found to convert SQL ResultSet to JSON Array.


Remember to import.

import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.ResultSet;

The convert method.

public static JSONArray convert(ResultSet resultSet) throws Exception {

	JSONArray jsonArray = new JSONArray();

	while ( {

		int columns = resultSet.getMetaData().getColumnCount();
		JSONObject obj = new JSONObject();

		for (int i = 0; i < columns; i++)
			obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));

	return jsonArray;


Where I found the code.