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

How to wrap JSON response in a parent object

我的 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"
     }
  ]
} 

控制器:

   @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);
}

用户模型class:

@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;
    }
}

然后 return 在您的控制器方法中 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);
}