我应该如何处理可以具有多种类型的RequestBody的Java POST?
问题描述:
所以我有一个春天RestController和我的一个端点是用来传递到我的RequestBody作为这样一个通用类型的对象上执行操作:我应该如何处理可以具有多种类型的RequestBody的Java POST?
似乎@PostMapping("/endpoint")
public <T extends Comparable<T>> ResponseEntity<Integer> balancingPost(@RequestBody MyCustomObject<T> mco)
所以经过大量的搜索也不会这样可以在没有明确说明某一点的类型的情况下完成。然而,就我看来,我的控制器无法知道类型(尽管如此,调用POST的程序)。那我该如何处理呢?有没有办法发布我的T级,并以某种方式映射它?
答
尝试以下
public ResponseEntity<?> balancingPost(@RequestBody MyCustomObject<T> mco) {
ResponseEntity<?> response = null;
try {
/*Some condition*/
if (!auth.equals(authCode)) {
response = new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
} else {
MyModel model = service.getModel();
response = new ResponseEntity<>(model, HttpStatus.OK);
}
} catch (Exception ex) {
response = new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
ex.printStackTrace();
}
return response;
}