讓我們看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