简体   繁体   English

Spring Boot Rest 控制器:在返回类型中添加文本

[英]Spring Boot Rest controller: adding text in the return type

I have a SpringBoot app.我有一个 SpringBoot 应用程序。 with a RestController使用 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:因为我想在 DataTable ajax 调用中使用这个控制器,所以我需要在开头添加这段代码:

{
  "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> :正如我所评论的,您只需要返回一个Map而不是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:将您的 List 包装到带有data字段的类中并返回它:

     class Result { List<AggregCalcTrainsXCompany> data; }
  2. (as comment suggested) Return Map<String, List<AggregCalcTrainsXCompany>> (如建议的评论)返回Map<String, List<AggregCalcTrainsXCompany>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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