How to convert a Java resultset into JSON?

前端 未结 10 1990
清酒与你
清酒与你 2020-11-30 04:58

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

相关标签:
10条回答
  • 2020-11-30 05:23

    It's pretty easy if you want to use Spring:

    @RestController
    public class MyController
    
      @Autowired
      private JdbcTemplate jdbcTemplate;
    
      @RequestMapping("/")
      List<Map<String,Object>> getAll() {
        return jdbcTemplate.queryForList("select * from my_table");
      }
    }
    

    In mvc-dispatcher-servlet.xml, you'd setup your JdbcTemplate like this:

    <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
      <property name="dataSource">
        ...data source config...
      </property>
    </bean>
    

    Jackson should be in your classpath (ie a Maven dependency).

    0 讨论(0)
  • 2020-11-30 05:25

    If you utilizing the Spring' JDBCTemplate for executing stored functions which returns cursor as list of the tables entries and, in turns, you wish to map it as a list of the specified bean, then there is the most neat solution:

    import com.fasterxml.jackson.databind.ObjectMapper;
    
    ...
    
    final static ObjectMapper mapper = new ObjectMapper();
    
    ...
    
    <T> List<T> populateExecuteRetrieve(SimpleJdbcCall call, Map inputParameters, Class<T> outputClass) {
        List<?> sqlResult;
        sqlResult = call.executeFunction(ArrayList.class, parameter);
        return sqlResult
                .stream()
                .map(entry -> mapper.convertValue(entry, outputBeanClass))
                .collect(Collectors.toList());
    }
    

    You are welcome!

    Happy coding!

    0 讨论(0)
  • 2020-11-30 05:34

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 05:37

    Many people have answered the question correctly. But, I think i can add more value to the post with the following small snippet of code. It uses the Apache-DBUtils and the Gson library.

    public static String resultSetToJson(Connection connection, String query) {
            List<Map<String, Object>> listOfMaps = null;
            try {
                QueryRunner queryRunner = new QueryRunner();
                listOfMaps = queryRunner.query(connection, query, new MapListHandler());
            } catch (SQLException se) {
                throw new RuntimeException("Couldn't query the database.", se);
            } finally {
                DbUtils.closeQuietly(connection);
            }
            return new Gson().toJson(listOfMaps);
        }
    
    0 讨论(0)
  • 2020-11-30 05:38
    • Convert resultset into List<Map<String, Object>> (each map contains a row with column names as keys and column content as value, List is a list of such rows)
    • Use Gson or Jackson library to covert this object into JSON.
    0 讨论(0)
  • 2020-11-30 05:44

    You can use any JSON library.

    The following is an implementation of this, return a list, with each element a JSON Object:

    /*
     * Convert ResultSet to a common JSON Object array
     * Result is like: [{"ID":"1","NAME":"Tom","AGE":"24"}, {"ID":"2","NAME":"Bob","AGE":"26"}, ...]
     */
    public static List<JSONObject> getFormattedResult(ResultSet rs) {
        List<JSONObject> resList = new ArrayList<JSONObject>();
        try {
            // get column names
            ResultSetMetaData rsMeta = rs.getMetaData();
            int columnCnt = rsMeta.getColumnCount();
            List<String> columnNames = new ArrayList<String>();
            for(int i=1;i<=columnCnt;i++) {
                columnNames.add(rsMeta.getColumnName(i).toUpperCase());
            }
    
            while(rs.next()) { // convert each object to an human readable JSON object
                JSONObject obj = new JSONObject();
                for(int i=1;i<=columnCnt;i++) {
                    String key = columnNames.get(i - 1);
                    String value = rs.getString(i);
                    obj.put(key, value);
                }
                resList.add(obj);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resList;
    }
    
    0 讨论(0)
提交回复
热议问题