Reputation: 2480
my motive is to write one generic save method in REST API. User will send the entity in Request body such that depending upon Request Mapping String it should be converted to entity.
Why i am want this, because in my case there are as many as 50-60 entities and as per my understanding i have to write many controllers.
I am trying to achieve something like this.
@RequestMapping(value = "/{entity}", method = RequestMethod.POST)
@ResponseBody
public Object performSave(@PathVariable String entity
@RequestBody Object entity) {
switch(entity){
case "employee"
return employeeService.save((Employee)entity);
case "Boss"
return bossService.save((Boss)entity);
default:
return null;
}
but i am not able to do that because Spring cannot convert the JSON Request into java.lang.Object.
what possible solutions i have ?
If my question do not make sense to you, please let me know ,i will provide additional details.
Thanks in advance.
Upvotes: 0
Views: 1375
Reputation: 88
It can be done with only one controller. One possible implementation would be using JsonSubTypes and Java inheritance.
It is done by moddeling request body objects (entities, in the original question) that extend an abstract class. Request body parameter in the controller's method then has the type of the abstract class.
Upvotes: 0
Reputation: 189
I don't think that is possible as the underlying mapper would need the concrete class which the json is parsed to. The parameter is simply a reference to the actual object.
Something to take note of is that when using REST and getting the benefit from it is not only having simple urls to call. One has to design APIs to be RESTfull. I would advice you to read up on that concept before going down this path you are heading.
Upvotes: 1