Java Jackson@JsonSubTypes的替代方案

Java Jackson@JsonSubTypes的替代方案,java,json,spring-mvc,jackson,Java,Json,Spring Mvc,Jackson,Jackson框架提供了基于注释的方法来在序列化过程中发出类型信息 我不想在我的超类(Animal)中使用@JsonSubTypes注释 相反,我想告诉我的子类,即狗和大象,动物是它们的父母 有没有什么方法可以不用在Animal类中使用注释就可以做到这一点 如果是,请提供示例,以便在可能的情况下执行相同的操作 下面是我试图解析的案例。test接收的JSON包含“type”字段为“dog”或“elephant” 我想将这两个类注册为“Animal”类的子类型,但不想在Animal中使用@JsonS

Jackson框架提供了基于注释的方法来在序列化过程中发出类型信息

我不想在我的超类(Animal)中使用@JsonSubTypes注释

相反,我想告诉我的子类,即狗和大象,动物是它们的父母

有没有什么方法可以不用在Animal类中使用注释就可以做到这一点

如果是,请提供示例,以便在可能的情况下执行相同的操作

下面是我试图解析的案例。test接收的JSON包含“type”字段为“dog”或“elephant”

我想将这两个类注册为“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;

    }
}

这个答案将有助于实现你想要的,但方式略有不同。 创建一个具有必要配置的单独类,并将其注册为动物类的序列化/反序列化配置类,如下所示:

配置类:

要序列化或反序列化:

ObjectMapper mapper=new ObjectMapper();
mapper.getDeserializationConfig().AddMixinNotations(Animal.class,PolymorphicAnimalMixIn.class);
mapper.getSerializationConfig().AddMixinNotations(Animal.class,PolymorphicAnimalMixIn.class);
//带有动物集合的示例类
班级{
公共收藏

您可以使用图书馆

使用它,您可以创建如下所示的ObjectMapper:

ObjectMapper objectMapper = new ObjectMapper();

 MoonwlkerModule module =
   MoonwlkerModule.builder()
     .fromProperty("type").toSubclassesOf(Animal.class)
     .build();

 objectMapper.registerModule(module);

然后使用该映射器进行(反)序列化。Moonwlker网站包含更多详细信息和配置选项。

您可以通过调用objectMapper.registerSubtypes(Dog.class、Elephant.class)注册子类型方法。是您正在寻找的吗?谢谢Alexey。请您用一些示例来支持您的答案。我尝试了objectMapper.registerSubtypes(Dog.class,Elephant.class),但没有成功。我包括了objectMapper mapper=new objectMapper();mapper.registerSubtypes(Dog.class、大象.class);在MyController类的“save”方法(REST服务)中。不再有效:/@facundofarias现在什么有效?
mapper.addMixIn()
不起作用。
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);
ObjectMapper objectMapper = new ObjectMapper();

 MoonwlkerModule module =
   MoonwlkerModule.builder()
     .fromProperty("type").toSubclassesOf(Animal.class)
     .build();

 objectMapper.registerModule(module);