Before AJAX was popular, it was possible to convert between id's and entities by using a custom property editor and registering that in your controllers. So if you had a User
form backing object that contained a Company
, if company.id
was 5, Spring would call your custom property editor to so that you could go fetch the Company with id 5
and set it onto your user.company
property.
Now in the Ajax way of doing things, we have similar requirements. Instead of using a form backing object, we want to do an HTTP POST or PUT of a User
object as JSON data and have Spring automatically convert that JSON to a User object on our behalf. Spring has made this possible with the @RequestBody
annotation, and by using Jackson to marshall the JSON back and forth to Java objects.
This is just a fictitious example. Imagine a User
containing a Company
object with the appropriate getters/setters.
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void create(@Valid @RequestBody User user) {
userService.saveUser(user);
}
Since property editors are a thing of the past as far as Spring is concerned, we are expected to use the new Conversion Service API. For my application, I have successfully created a factory that does what my old property editor did before - converting id's back to entities.
My question is, how can I get Spring to call into the conversion service during or after Jackson marshals the JSON data? I know it is possible to create a custom JsonDeserializer
, but I find writing/testing these to be a pain and lengthy process as I need to do it for a massive number of entities, and each deserializer would take anywhere from 60 to 200 lines of code each.
I'd love it if Spring could do the id to entity mapping for me on my behalf, just as it did for form backing objects. Is there a way?