Jackson控制多态的注解--JsonTypeInfo,JsonSubTypes,JsonTypeName

让我们看Jackson控制多态的注解:

  • @JsonTypeInfo – indicates details of what type information to include in serialization 指出序列化包含的类型信息细节
  • @JsonSubTypes – indicates sub-types of the annotated type 指出被注解类型的子类
  • @JsonTypeName – defines a logical type name to use for annotated class 定义被注解类使用的逻辑名称

让我们看使用这三个注解的例子--序列化/反序列化Zoo实体:

public class Zoo {
    public Animal animal;
 
    @JsonTypeInfo(
      use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, 
      property = "type")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat")
    })
    public static class Animal {
        public String name;
    }
 
    @JsonTypeName("dog")
    public static class Dog extends Animal {
        public double barkVolume;
    }
 
    @JsonTypeName("cat")
    public static class Cat extends Animal {
        boolean likesCream;
        public int lives;
    }
}

当我们序列化的时候:

@Test
public void whenSerializingPolymorphic_thenCorrect()
  throws JsonProcessingException {
    Zoo.Dog dog = new Zoo.Dog("lacy");
    Zoo zoo = new Zoo(dog);
 
    String result = new ObjectMapper()
      .writeValueAsString(zoo);
 
    assertThat(result, containsString("type"));
    assertThat(result, containsString("dog"));
}

序列化Dog的结果:

{
    "animal": {
        "type": "dog",
        "name": "lacy",
        "barkVolume": 0
    }
}

参考链接:

https://www.baeldung.com/jackson-annotations

转载于:https://www.cnblogs.com/windyWu/p/11243188.html

你可能感兴趣的:(Jackson控制多态的注解--JsonTypeInfo,JsonSubTypes,JsonTypeName)