简体   繁体   中英

Spring Boot Rest controller: adding text in the return type

I have a SpringBoot app. with a RestController

@RestController
@RequestMapping("/api/aggreg")
public class AggregRestController  {

@GetMapping("/list")
    public List<AggregCalcTrainsXCompany> aggregList  ()
            throws IOException, URISyntaxException, DataAccessException, SQLException {

        return aggregService.findAll();
    }
}

Since I want to use this controller in a DataTable ajax call, I would need to add this piece of code in the beginning:

{
  "data":

and } at the end to make it work, but I don't know if this is possible

As I commented, you simply need to return a Map instead of a List<AggregCalcTrainsXCompany> :

@RestController
@RequestMapping("/api/aggreg")
public class AggregRestController  {

    @GetMapping("/list")
    public Map<String, List<AggregCalcTrainsXCompany>> aggregList  ()
            throws IOException, URISyntaxException, DataAccessException, SQLException {
        Map<String, List<AggregCalcTrainsXCompany>> m = new HashMap<>();
        m.put("data", aggregService.findAll());

        return m;
    }
}

The map will be serialized as

{
   "data" : <here the result from your aggregtation> 
}

You have two options:

  1. Wrap your List into class with data field and return it:

     class Result { List<AggregCalcTrainsXCompany> data; }
  2. (as comment suggested) Return Map<String, List<AggregCalcTrainsXCompany>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM