Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient way to convert jdbctemple result to json?

One Way is to convert the List< Map < String, Object>> into List(object); Given Below

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

Is there any effiecient way to directly convert the jdbcTemplate result into json object?

like image 448
Kunal Batra Avatar asked Dec 25 '22 04:12

Kunal Batra


1 Answers

If you are using Maven as you build script. Add following dependency

<!-- 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>

Modify Code as shown below

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

However if you are using Spring 4+ MVC, I would recommend you to use @RestController

Which does most of the job for you here is an example for you, here is simple example

   @RestController
   class MyTestClass{

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

        return jdbcTemplate.queryForList(query);        
    }

}

Note: In Both Above cases you need to convert The Object class to a Exact class to work.

like image 162
Karthik Prasad Avatar answered Dec 27 '22 11:12

Karthik Prasad