json - 将 jdbctemplate 结果转换为 json 的最有效方法?

标签 json spring spring-mvc spring-jdbc jdbctemplate

一种方法是转换 List< Map < String, Object>>进入 List(object);下面给出

List<Map<String, Object>> ls = jdbcTemplate.queryForList(query);

List<Users> ls_o =  new ArrayList<>(ls_o);
        for (Map<String, Object> row : ls) {
        ls_o.add(row);

        }
 return new ResponseEntity<List<User>>(ls_o, HttpStatus.OK);

有没有什么有效的方法可以将 jdbcTemplate 结果直接转换为 json 对象?

最佳答案

如果您在构建脚本时使用 Maven。添加以下依赖

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.5</version>
</dependency>

修改代码如下图
   private final ObjectMapper mapper = new ObjectMapper();

    public ResponseEntity myMethod(){

    List<Map<String, Object>> ls = jdbcTemplate.queryForList(query);        
    final String str = mapper.writeValueAsString(ls);
    return new ResponseEntity<List<User>>(str, HttpStatus.OK);
}

但是,如果您使用的是 Spring 4+ MVC,我建议您使用 @RestController

在这里为您完成大部分工作的是一个例子,这是一个简单的例子
   @RestController
   class MyTestClass{

    @RequestMapping("/myMethod")
    public List<Map<String, Object>> myMethod(){

        return jdbcTemplate.queryForList(query);        
    }

}

注:在上述两种情况下,您都需要将 Object 类转换为 Exact 类才能工作。

关于json - 将 jdbctemplate 结果转换为 json 的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960540/

相关文章:

spring - 为什么以及何时在 Spring 中使用 @Inject 而不是 @Autowired?

java - 这个 Spring Oauth2 配置文件有什么问题?

json - 如何从 JSON API 调用项目并添加到 TabBar - Flutter

json - 为什么 Kotlin Object 类到 json 对象为 null?

java - Spring集成Java DSL : strategy to handle errors/exceptions?

spring - 是否可以填充 spring util :list via properties file?

Spring:设置一个简单的 PropertyPlaceholderConfigurer 示例

spring-mvc - 使用 Spring 框架自定义异常消息

ios - 使用 UICollectionReusableView 对单元格进行分组

javascript - 节点 : How to preserve "\u00a0" in JSON string during a merge with other JSON