Reputation: 838
I am looking for advice on the best practice for handling the following scenario.
Given a Java based Web API that accepts JSON requests we need to map the JSON object to Java. This question is about the case where the Java object is a parametric type. For my particular case I am using Spring and the MappingJacksonHttpMessageConverter to do the mapping.
Example REST Service
@RequestMapping(method = RequestMethod.POST)
public void updateContainer(@RequestBody Container<?> container) {
realService.updateContainer(container);
}
Example Parametric Type
public class Container<T extends ContainerItem> {
private T containerItem;
...
}
When I call this method I will get a 400 error (bad request) because the type of Container is erased at runtime and Jackson doesn't know how to map my containerItem (since it has no idea what type to map to).
I have a very basic solution implemented, in which I add a field to the JSON data which specifies the Java classname of containerItem, and then added a custom HttpMessageConverter which uses this classname to construct a parametric JavaType which the Jackson ObjectMapper can then use to do the mapping, but I am wondering if anyone has a better way of handling this?
Upvotes: 1
Views: 725
Reputation: 49935
A solution would be to declare a parametric type and use this as the target of @RequestBody
this way:
public class MyCustomTypeContainer extends Container<SubContainerItem> {
..
}
public void updateContainer(@RequestBody MyCustomTypeContainer container) {
realService.updateContainer(container);
}
Note, that the MyCustomTypeContainer
has to be a parametric type(generic types fully realized). This potentially means that you may have to create a subtype for every containerItem type.
See here for another question along the same lines.
Upvotes: 4