Skip to content

Instantly share code, notes, and snippets.

@azakordonets
Created June 5, 2015 05:55
Show Gist options
  • Select an option

  • Save azakordonets/da31d9e74369a9d71b1c to your computer and use it in GitHub Desktop.

Select an option

Save azakordonets/da31d9e74369a9d71b1c to your computer and use it in GitHub Desktop.
This class helps you easily to convert ResultSet(result of DB querry) into JSON or XML
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.ResultSet;
/**
* Utility for converting ResultSets into some Output formats
* @author marlonlom
*/
public class Convertor {
/**
* 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();
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;
}
/**
* Convert a result set into a XML List
* @param resultSet
* @return a XML String with list elements
* @throws Exception if something happens
*/
public static String convertToXML(ResultSet resultSet)
throws Exception {
StringBuffer xmlArray = new StringBuffer("<results>");
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
xmlArray.append("<result ");
for (int i = 0; i < total_rows; i++) {
xmlArray.append(" " + resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase() + "='" + resultSet.getObject(i + 1) + "'"); }
xmlArray.append(" />");
}
xmlArray.append("</results>");
return xmlArray.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment