Как обернуть JSON-ответ в родительский объект - PullRequest
1 голос
/ 30 апреля 2019

Текущий ответ от моей службы 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 Ответ

1 голос
/ 30 апреля 2019

Вы можете создать новый объект для сериализации:

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