我正在使用Spring Boot。写作休息api' s 对于相同的api url,请求json结构各不相同 我们有什么方法可以应用工厂设计或其他东西
@RequestMapping(value = "/myservice/{type}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> myServiceApi(@PathVariable String type,
@RequestBody SomeClass1 somereq) {
// here based on type , the RequestBody can be either SomeClass1 or SomeClass2
// both the SomeClass1 and SomeClass2 has nothing in common .
}
上面的代码只有在请求json是SomeClass1格式时才有效,但是我需要它接受{SomeClass1,SomeClass2}
答案 0 :(得分:3)
您可以将JSON作为String传递到控制器方法中,然后将其映射到您希望需要的任何对象:
@RequestMapping(value = "/myservice/{type}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> myServiceApi(@PathVariable String type,
@RequestBody String somereq) {
ObjectMapper mapper = new ObjectMapper();
if (<something that indicates SomeClass1>) {
SomeClass1 someClass1 = mapper.readValue(somereq, SomeClass1.class);
} else if (<something that indicates SomeClass2>) {
SomeClass2 someClass2 = mapper.readValue(somereq, SomeClass2.class);
}
...
}
虽然说实话,如果你真的期待具有完全不同结构的机构,我的建议是为这些机构单独调用API。