Java SQL ResultSet to convertResultSetToJSON(ResultSet resultSet)

Here you can find the source of convertResultSetToJSON(ResultSet resultSet)

Description

Convert a result set into a JSON Array

License

Apache License

Parameter

Parameter Description
resultSet a parameter

Exception

Parameter Description
Exception an exception

Return

a JSONArray

Declaration

public static JSONArray convertResultSetToJSON(ResultSet resultSet) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    /**//www  . j av a 2 s. co m
     * Convert a result set into a JSON Array
     * 
     * @param resultSet
     * @return a JSONArray
     * @throws Exception
     */
    public static JSONArray convertResultSetToJSON(ResultSet resultSet) throws Exception {
        JSONArray jsonArray = new JSONArray();

        if (resultSet != null) {
            while (resultSet.next()) {
                int total_rows = resultSet.getMetaData().getColumnCount();
                JSONObject obj = new JSONObject();
                for (int i = 0; i < total_rows; i++) {
                    int colNextIndex = i + 1;
                    obj.put(resultSet.getMetaData().getColumnLabel(colNextIndex).toLowerCase(),
                            resultSet.getObject(colNextIndex));
                }
                jsonArray.put(obj);
            }
        }

        return jsonArray;
    }
}

Related

  1. convert(int sqlType, String type, ResultSet rs, String name)
  2. convert(ResultSet rs)
  3. convertResultSetToMap(final ResultSet rs)
  4. convertToMap(Map metaData, ResultSet rs)
  5. resultSet2List(ResultSet rs)
  6. resultSet2Map(ResultSet rs)