Convert List<Object[]> to JSON

2019-07-22 03:49发布

问题:

Hi guys!

Can someone helps me, how to convert my HQL query results to JSON with list of objects and get it with rest service.

Here is my service method which returns qyery result list:

   @Override
    public List<Object[]> getAllDepartments() {
        List<Object[]> list;
        Query query =  entityManager.createQuery("SELECT dp.name, avg (wr.salary) FROM Worker wr join wr.department dp GROUP BY dp.name");
        list =  query.getResultList();
        return list;
    }

And my Spring RESTfull Controller:

@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public JsonNode getAllDeps() {
    List<Object[]> list  = departmentService.getAllDepartments();
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Integer> resultMap = new HashMap<String, Integer>(list.size());
    for (Object[] result : list)
        resultMap.put((String)result[0], ((Double)result[1]).intValue() );
    final JsonNode json = objectMapper.valueToTree(resultMap);
    return json;
}

Now my service responce me json with data in thats look : {"Security":1500,"Economical":1850,"IT":2000}

But i need in that(list of objects):

[{name:"Security",salary:"1500"},{name:"Economical",salary:1850},{name:"IT",salary:2000}]

Thanks for help.

回答1:

Just return the list from the controller method

@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public List<Object[]> getAllDeps() {
    List<Object[]> list  = departmentService.getAllDepartments();
    return list;
}

The @ResponseBody annotation does the transformation for you.