0

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?

Andna
  • 6,539
  • 13
  • 71
  • 120
  • In your sample you have shown a concrete type - `OpenQuestionAnswer`, are you getting this error even with a concrete type? Can you try lowering the log level to DEBUG and see if anything else shows up – Biju Kunjummen Aug 11 '12 at 15:08
  • Seems obvious, but are you referencing methods to your concrete class in your JSON POST (can't assume not seeing the code)? You might have to give up on inheritance and go with composition instead (http://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition) – nickdos Aug 12 '12 at 06:11

1 Answers1

3

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.

mavarazy
  • 7,562
  • 1
  • 34
  • 60