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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With