为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

千万里不及你 2022-11-02 10:38:02
我的 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);}用户模型类:@Document(collection = "user")public class User { @Id private String id; private String email;}我该如何实施?
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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


class ResponseWrapper {

    private List<User> elements;


    ResponseWrapper(List<User> elements) {

        this.elements = elements;

    }

}

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

}


查看完整回答
反对 回复 2022-11-02
  • 1 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信