Reputation: 6689
I have a class hierarchy. On the top of it there is a an abstract AnswerUnit class. There are two inheriting classes: OpenQuestionAnswer and MultipleChoiceQuestionAnswer.
I have a .jsp form that sends data (object serialized to JSON) to server with AJAX request and a method in controller to handle it.
@RequestMapping(value = "/test", method = RequestMethod.POST)
public @ResponseBody
String testPostMethod(@RequestBody
OpenQuestionAnswer answer) {
return "home";
}
I would like to be able to take "AnswerUnit answer" as the argument (abstract type instead of concrete type, so I could handle request from different views with one method). When I try to do it there is a problem - server respose is
400 BAD REQUEST he request sent by the client was syntactically incorrect.
I think that the reason is that Spring (Jackson?) isn't able to find out which concrete class he should create and use. On the client side I know what type of class I send to server. What is the proper way to tell server which concrete class should be created and filled with my request?
Upvotes: 0
Views: 2474
Reputation: 7735
I guess I'm late with response, but anyway:)
http://wiki.fasterxml.com/JacksonAnnotations
You can have this using Jackson Polymorphic type handling
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(value = {
@JsonSubTypes.Type(name = "answer", value = OpenQuestionAnswer.class),
@JsonSubTypes.Type(name = "multiple", value = MultipleChoiceQuestionAnswer.class)
})
public class AnswerUnit
...
But you would need to add "type" field to your client JSON.
Upvotes: 3