【问题标题】:How should I handle a Java POST that can have a RequestBody of multiple types?我应该如何处理可以具有多种类型的 RequestBody 的 Java POST?
【发布时间】:2017-10-06 19:52:16
【问题描述】:
所以我有一个 Spring RestController,我的一个端点用于对传递给我的 RequestBody 的通用类型对象执行操作,如下所示:
@PostMapping("/endpoint")
public <T extends Comparable<T>> ResponseEntity<Integer> balancingPost(@RequestBody MyCustomObject<T> mco)
因此,经过大量搜索后,如果没有在某个时候明确说明类型,似乎无法做到这一点。但是,就目前而言,我的控制器无法知道类型(尽管调用 POST 的程序确实如此)。那么我应该如何处理呢?有没有办法发布我的 T 类并以某种方式映射它?
【问题讨论】:
标签:
java
spring
rest
jackson
deserialization
【解决方案1】:
尝试关注
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;
}