The scenario
I am required to build an API that provides clients access to several kinds of objects that are stored in a DB (my DAO is Hibernate-based as of today). These can be GETted or POSTed.
Currently the GET signature is the following:
@RequestMapping(value = "/rest/{datatype}", method = RequestMethod.GET, produces = { "application/json" })
public @ResponseBody
Object[] getData(@PathVariable("datatype") String dataType,
WebRequest request) throws HttpException {
This means that depending on the data type in the URL I will be going to access a given repository and return an object of my business domain. It works fine so far.
For POST, I must be able to submit an object in JSON format, convert it to a class and store it into the database.
Obviously if I use postFunfData(SpecificDataType object) Jackson converts JSON to object successfully, but I don’t know the object type at compile time.
Another requirement is flexibility: When a new class is added to the domain, little code work has to be done to support the new datatype. In the GET ter I just add a switch to support the new datatype, instantiate correct repository with Spring and query the DB.
The question
How do I write a Spring MVC REST API that accepts "anything" as request body and allows me to convert from JSON to the correct object? Something like:
public void postData(@RequestBody Object objData){
if (objData instanceof Class1) {
Class1 obj = (Class1) objData;
Class1Repository.store(obj);
}
[...]
}
Possible answer
(Please provide your one if you find a better solution)
Create several simple APIs based on the same skeleton
This way when Spring MVC analyzes the path it finds the correct controller method that handles the request. Then it asks Jackson to convert the request body to the argument type detected by reflection.