@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "feetType",include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(name = "two", value = Animal.TwoFeetAnimal.class),
@JsonSubTypes.Type(name = "four", value = Animal.FourFeetAnimal.class),
})
public abstract class Animal {
String name;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "landType",include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(name = "land", value = FourFeetAnimal.LandAnimal.class),
@JsonSubTypes.Type(name = "water", value = FourFeetAnimal.WaterAnimal.class),
})
@Data
public static abstract class FourFeetAnimal extends Animal{
int feet;
@Data
public static class LandAnimal extends FourFeetAnimal{
String text1;
}
@Data
public static class WaterAnimal extends FourFeetAnimal{
String text2;
}
}
public static class TwoFeetAnimal extends Animal{
}
}
Test
public class Test {
public static void main(String[] args) throws JsonProcessingException {
Animal.FourFeetAnimal.LandAnimal landAnimal = new Animal.FourFeetAnimal.LandAnimal();
landAnimal.setText1("text1");
landAnimal.setName("陆地动物");
landAnimal.setFeet(4);
ObjectMapper objectMapper = new ObjectMapper();
final String string = objectMapper.writeValueAsString(landAnimal);
System.out.println(string);
}
}
Test
result
The result ignores the feetType in Animal. An error is also reported when deserializing. In this case, what should I do?thanks all.