问题描述
我有一个类层次结构。在它的顶部有一个抽象AnswerUnit类。有两种继承类:OpenQuestionAnswer和MultipleChoiceQuestionAnswer。
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.
我有发送数据(序列化到JSON对象)到服务器AJAX请求和控制的方法来处理它的.jsp的形式。
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";
}
我希望能够采取AnswerUnit回答作为参数(抽象类型,而不是具体类型,这样我就可以从不同的角度处理请求,一种方法)。当我尝试这样做有一个问题 - 服务器respose是
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错误的请求,他要求客户端发送的是语法不正确。
我认为,原因在于春(杰克逊?)是不是能够找出具体的类,他应该创建和使用。在客户端,我知道我发送到服务器是什么类型的类。什么是正确的方法来判断哪些具体的类应创建并充满了我的请求,服务器?
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?
推荐答案
我想我下旬响应,但无论如何:)
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
...
但是,你需要类型字段添加到您的客户端的JSON。
But you would need to add "type" field to your client JSON.
这篇关于Spring MVC的+ JSON在@ResponseBody +继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!