How to convert a Java resultset into JSON?

前端 未结 10 2068
清酒与你
清酒与你 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:45

    If you are using JSON I recommend the Jackson JSON library.

    http://wiki.fasterxml.com/JacksonHome

    The jar files can be found here:

    http://wiki.fasterxml.com/JacksonDownload

    Here is the generic code I use to convert any result set into a Map<> or List< Map<> > Converting this to JSON using JacksonJSON is pretty straight forward (See Below).

    package com.naj.tmoi.entity;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class EntityFactory {
    
        public EntityFactory(Connection connection, String queryString) {
            this.queryString = queryString;
            this.connection = connection;
        }
    
        public Map findSingle(Object[] params) throws SQLException {
            List> objects = this.findMultiple(params);
    
            if (objects.size() != 1) {
                throw new SQLException("Query did not produce one object it produced: " + objects.size() + " objects.");
            }
    
            Map object = objects.get(0);  //extract only the first item;
    
            return object;
        }
    
        public List> findMultiple(Object[] params) throws SQLException {
            ResultSet rs = null;
            PreparedStatement ps = null;
            try {
                ps = this.connection.prepareStatement(this.queryString);
                for (int i = 0; i < params.length; ++i) {
                    ps.setObject(1, params[i]);
                }
    
                rs = ps.executeQuery();
                return getEntitiesFromResultSet(rs);
            } catch (SQLException e) {
                throw (e);
            } finally {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
            }
        }
    
        protected List> getEntitiesFromResultSet(ResultSet resultSet) throws SQLException {
            ArrayList> entities = new ArrayList<>();
            while (resultSet.next()) {
                entities.add(getEntityFromResultSet(resultSet));
            }
            return entities;
        }
    
        protected Map getEntityFromResultSet(ResultSet resultSet) throws SQLException {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            Map resultsMap = new HashMap<>();
            for (int i = 1; i <= columnCount; ++i) {
                String columnName = metaData.getColumnName(i).toLowerCase();
                Object object = resultSet.getObject(i);
                resultsMap.put(columnName, object);
            }
            return resultsMap;
        }
        private final String queryString;
        protected Connection connection;
    }
    

    In the servlet I convert the List into JSON using the com.fasterxml.jackson.databind.ObjectMapper which converts Java Generics into a JSON String.

        Connection connection = null;
        try {
            connection = DataSourceSingleton.getConnection();
            EntityFactory nutrientEntityFactory = new EntityFactory(connection, NUTRIENT_QUERY_STRING);
            List> nutrients = nutrientEntityFactory.findMultiple(new Object[]{});
    
            ObjectMapper mapper = new ObjectMapper();
    
            String json = mapper.writeValueAsString(nutrients);
    
    
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
        } catch (SQLException e) {
            throw new ServletException(e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new ServletException(e);
                }
            }
        }
    

    You can pass in Parameters to the PreparedStatement like this:

    String name = request.getHeader("name");
    EntityFactory entityFactory = new EntityFactory(DataSourceSingleton.getConnection(), QUERY_STRING);
    Map object = entityFactory.findSingle(new String[]{name});
    
    
    private static final String QUERY_STRING = "SELECT NAME, PASSWORD, TOKEN, TOKEN_EXPIRATION FROM USER WHERE NAME = ?";
    

    }

提交回复
热议问题