如何将ResultSet对象转换为JSON格式输出

Sri*_*nta 6 ajax jquery json jsp resultset

触发查询后我有一个ResultSet.请告诉我如何将其转换为JSP中的JSON输出.

在第二阶段,让我们假设我们有一个JSON输出,如在这个链接> http://inknpost.com/eshopping/json.jsp

$ .getJSON();正在访问上述文件; 在另一个文件中.

请告诉我如何在页面的不同行中显示"名称"和"部门".

Bal*_*usC 15

创建一个可重用的Javabean类,它表示一行,一个实体.

public class Category {
    private Long id;
    private String name;
    private String department;

    // Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate.
}
Run Code Online (Sandbox Code Playgroud)

创建一个可重用的DAO类,它ResultSet以通常的JDBC方式映射到那些Javabeans的集合.

public class CategoryDAO {
    private static final String SQL_LIST = "SELECT id, name, department FROM category";
    // ...

    public List<Category> list() throws SQLException {
        List<Category> categories = new ArrayList<Category>();

        try (
            Connection connection = database.getConnection();
            PreparedStatement statement = connection.prepareStatement(SQL_LIST);
            ResultSet resultSet = statement.executeQuery();
        ) {
            while (resultSet.next()) {
                Category category = new Category();
                category.setId(resultSet.getLong("id"));
                category.setName(resultSet.getString("name"));
                category.setDepartment(resultSet.getString("department"));
                categories.add(category);
            }
        }

        return categories;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

创建一个servlet类,它使用JSON序列化器/反序列化器,它能够在Javabeans的一个arbirary集合和一个JSON String之间进行转换,例如Google Gson.

@WebServlet("/categories.json")
public class CategoriesJsonServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Category> categories = categoryDAO.list();
            String categoriesJson = new Gson().toJson(categories);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(categoriesJson);
        } catch (SQLException e) {
            throw new ServletException("DB error", e);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

通过调用它http://localhost:8080/contextname/categories.json.不,没有涉及JSP.您不应该将JSP用于HTML以外的输出格式.

最后,在jQuery中,只需按常规$.getJSON()方式访问它.

$('#somebutton').click(function() {
    $.getJSON('categories.json', function(categoriesJson) {
        var $table = $('<table>').appendTo($('#somediv'));
        $.each(categoriesJson, function(index, category) {
            $('<tr>').appendTo($table)
                .append($('<td>').text(category.id))
                .append($('<td>').text(category.name))
                .append($('<td>').text(category.department));
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

  • @BalusC很棒的解决方案,如果没有你,stackoverflow会不一样!:) (3认同)
  • 非常感谢干净和有组织的代码 (2认同)