Jackson 框架提供了基于注解的方法来在序列化过程中发出类型信息。
我不想在我的父类(super class)(动物)中使用@JsonSubTypes 注释。
相反,我想告诉我的子类,即 Dog 和 Elephant,Animal 是它们的父类。
有没有在 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;
}
}
最佳答案
这个答案将有助于实现您想要的,但方式略有不同。 创建一个具有必要配置的单独类,并将其注册为 Animal 类的序列化/反序列化配置类,如下所示:
Configuration Class:
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Elephant.class, name = "cat"),
@Type(value = Dog.class, name = "dog") })
abstract class PolymorphicAnimalMixIn {
//Empty Class
}
To serialize or deserialize:
ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().addMixInAnnotations(Animal.class, PolymorphicAnimalMixIn.class);
mapper.getSerializationConfig().addMixInAnnotations(Animal.class, PolymorphicAnimalMixIn.class);
//Sample class with collections of Animal
class Zoo {
public Collection<Animal> animals;
}
//To deserialize
Animal animal = mapper.readValue("string_payload", Zoo.class);
//To serialize
Animal animal = mapper.writeValueAsString(zoo);
引用信用:example 5
关于java - 替代 Jackson @JsonSubTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24631923/