dimanche 29 mars 2015

Using Spring MVC projections with JSON and Jackson

In the new version of Spring Data (Fowler), one can pass an interface to Spring MVC controller actions, and Spring Data will then automatically create a proxy implementation and bind values to this proxy object.


An example is given in the blog post that describes some of the new features in Spring Data Fowler:



interface Form {
@NotBlank String getName();
@NotBlank String getText();
}

@Controller
@RequestMapping(value = "/guestbook")
class GuestbookController {
@RequestMapping(method = RequestMethod.GET)
String guestbook(Form form, Model model) { ... }

@RequestMapping(method = RequestMethod.POST)
String guestbook(@Valid Form form, Errors errors, Model model) { ... }
}


My question is if this can also be done when deserializing JSON with Jackson? For instance, like this:



interface Form {
@NotBlank String getName();
@NotBlank String getText();
}

@Controller
@RequestMapping(value = "/guestbook")
class GuestbookController {
@RequestMapping(method = RequestMethod.POST)
String guestbook(@Valid @RequestBody Form form) { ... }
}


However, this gives the following exception:



Can not construct instance of Form, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information



I understand what the problem is, but is there a solution that does not require me to create a class that implements my interface or write a lot of code? One that is simpler than this approach. Because otherwise I might as well go with a DTO approach, but I just found it to be super cool if I could simply use an interface as in the example.


I can use a DTO class just fine with the above approach (or avoid using JSON), but using an interface like in the blog post's example would be neat. But is this possible with the Jackson library when deserializing JSON?


Aucun commentaire:

Enregistrer un commentaire