Jackson框架提供了基于注释的方法,用于在序列化过程中发出类型信息.
我不想在我的超类(Animal)中使用@JsonSubTypes注释.
相反,我想告诉我的SubClasses,即狗和大象,动物是他们的父母.
是否有任何方法可以在不使用Animal类中的注释的情况下执行此操作.
如果是,请提供如果可能的话做同样的例子.
以下是我试图解决的情况."测试"接收的JSON,包含"类型"字段为"狗"或"大象".
我想将这两个类注册为"Animal"类的子类型,但不想在Animal中使用@JsonSubTypes.
任何帮助,将不胜感激.提前致谢.
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
abstract class Animal(){
private String sound;
private String type;
//getters and setters
}
@JsonTypeName("dog")
Class Dog extends Animal(){
//some attributes.
//getters and setters
}
@JsonTypeName("elephant")
Class Elephant extends Animal(){
//some attributes.
//getters and setters
}
@Controller
public class MyController {
//REST service
@RequestMapping( value = "test")
public @ResponseBody String save(@RequestBody Animal animal){
System.out.println(animal.getClass());
return success;
}
}
Run Code Online (Sandbox Code Playgroud)