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

问题描述 投票:1回答:1

我的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;
}

我该如何实现呢?

java json spring-rest
1个回答
1
投票

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.