亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 JSON 響應包裝在父對象中

如何將 JSON 響應包裝在父對象中

千萬里不及你 2022-11-02 10:38:02
我的 Spring REST 服務的當前響應如下:[    {        "id": "5cc81d256aaed62f8e6462f4",        "email": "[email protected]"    },    {        "id": "5cc81d386aaed62f8e6462f5",        "email": "[email protected]"    }]我想將它包裝在一個 json 對象中,如下所示: {   "elements":[      {        "id": "5cc81d256aaed62f8e6462f4",        "email": "[email protected]"    },    {        "id": "5cc81d386aaed62f8e6462f5",        "email": "[email protected]"     }  ]} 控制器:   @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 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號