Jackson @JsonSubTypes的替代方案

use*_*309 9 java json spring-mvc jackson

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)

Syn*_*taX 4

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

配置类:

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
}
Run Code Online (Sandbox Code Playgroud)

序列化或反序列化:

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);
Run Code Online (Sandbox Code Playgroud)

参考来源:示例 5