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

4

我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个回答

4
您可以创建一个新对象进行序列化:
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);
}

谢谢回复。但是我遇到了以下异常。 org.springframework.web.client.HttpClientErrorException: 406 null - GeekySelene
@GeekySelene,你是否使用“Accept:application/json”头来发出请求?你在“getPartnersByDate”的注释中指定了它会生成“application/xml”,但是在你的原始问题中看起来你想要json。也许可以将你的“@RequestMapping”更改为“produces =“application/json””。 - ChocolateAndCheese
我已经修复了它,但现在出现了这个错误。状态码为406,无法找到可接受的表示形式。 - GeekySelene
我可以通过为包装类添加getter方法来解决这个问题。谢谢。 - GeekySelene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接