I am using Spring Boot . Writing rest api's where for the same api url , the request json structure varies Is there any way we can apply Factory design or some thing else
@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 .
}
The above code will work only if the request json is in SomeClass1 format , but i needed it to accept among {SomeClass1 , SomeClass2}
You could do this by passing the JSON as a String into your controller method and then mapping this to whichever object you expect to need:
@PostMapping(value = "/myservice/{type}")
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);
}
}
Although to be honest if you really are expecting bodies with completely different structures my advice would be to just make separate API calls for these.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments