Alternative to Jackson @JsonSubTypes
Jackson框架提供了基于注释的方法,可在序列化过程中发出类型信息。
我不想在我的超类(动物)中使用@JsonSubTypes注释。
相反,我想告诉我的子类(即Dog和Elephant),Animal是它们的父母。
是否有任何方法可以在不使用Animal类中使用注释的情况下。
如果是,请提供的示例,如果可能的话。
以下是我要解决的情况。"测试"收到的JSON包含"类型"字段作为"狗"或"大象"。
我想将这两个类注册为"动物"类的子类型,但不想在Animal中使用@JsonSubTypes。
任何帮助将不胜感激。
预先感谢。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | @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:
1 2 3 4 5 6 7 8 9 10 11 12 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
参考信用:示例5
您可以使用Moonwlker库。
使用它,您可以像这样创建一个ObjectMapper:
1 2 3 4 5 6 7 8 | ObjectMapper objectMapper = new ObjectMapper(); MoonwlkerModule module = MoonwlkerModule.builder() .fromProperty("type").toSubclassesOf(Animal.class) .build(); objectMapper.registerModule(module); |
然后使用该映射器进行(反)序列化。 Moonwlker网站包含更多详细信息和配置选项。