由于使用JDBC连接器的MySQL查询,我得到了一个结果集。因此,我的工作是将结果集转换为JSON格式。这样我就可以将其作为AJAX响应发送到客户端。有人可以解释一下如何转换为JSON格式,因为我是Java和JSON的新手。

最佳答案

许多人正确地回答了这个问题。但是,我认为我可以使用以下一小段代码为该帖子添加更多值(value)。它使用Apache-DBUtilsGson库。

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);
    }

09-26 20:01