java - 如何将 JSON 响应包装在父对象中

标签 java json spring-rest

我的 Spring REST 服务的当前响应如下:

[
    {
        "id": "5cc81d256aaed62f8e6462f4",
        "email": "exmaplefdd@gmail.com"
    },
    {
        "id": "5cc81d386aaed62f8e6462f5",
        "email": "exmaplefdd@gmail.com"
    }
]

我想将其包装在 json 对象中,如下所示:

 {  
 "elements":[
      {
        "id": "5cc81d256aaed62f8e6462f4",
        "email": "exmaplefdd@gmail.com"
    },
    {
        "id": "5cc81d386aaed62f8e6462f5",
        "email": "exmaplefdd@gmail.com"
     }
  ]
} 

Controller :

   @RequestMapping(value = "/users", method = GET,produces = "application/xml")
   @ResponseBody
   public ResponseEntity<List<User>> getPartnersByDate(@RequestParam("type") String type, @RequestParam("id") String id) throws ParseException {

   List<User> usersList = userService.getUsersByType(type);
   return new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
}

用户模型类:

@Document(collection = "user")
public class User {

 @Id
 private String id;
 private String email;
}

我该如何实现这个?

最佳答案

您可以创建一个新对象来序列化:

class ResponseWrapper {
    private List<User> elements;

    ResponseWrapper(List<User> elements) {
        this.elements = elements;
    }
}

然后在 Controller 方法中返回 ResponseWrapper 的实例:

   @RequestMapping(value = "/users", method = GET,produces = "application/xml")
   @ResponseBody
   public ResponseEntity<ResponseWrapper> getPartnersByDate(@RequestParam("type") String type, @RequestParam("id") String id) throws ParseException {

   List<User> usersList = userService.getUsersByType(type);
   ResponseWrapper wrapper = new ResponseWrapper(usersList);
   return new ResponseEntity<ResponseWrapper>(wrapper, HttpStatus.OK);
}

关于java - 如何将 JSON 响应包装在父对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923905/

相关文章:

java - 逐行将字符串写入文本文件时避免重复

java - 通过 Java 将 Ubuntu 10.4 连接到 MS SQL DB 的问题

javascript - 通过值比较合并 JSON 对象

java - Spring REST 将字段添加到 404 响应代码

json - 如何强制`.andExpect(jsonPath()`)返回Long/long而不是int以获取 jackson 解析器的int数

java - 在 AS400 上通过 Java 传输运行时进程执行 (cobol obj) 的结果时出现 MalformedInputException

java - JSP+Jetty项目上的Jasper异常

json - 吉拉 API |错误 : "Operation value must be a string" - trying to set value nested two levels deep

javascript - 如果字段返回 TypeError,则忽略 JSON 解析错误

java - Jpa 存储库查询 - java.lang.Object;不能转换到模型