如果你有一个容器类,Jackson 应该反序列化为容器类中的类型。我已将 A 重命名为 Animal,B 重命名为 Bird。
public class Container {
public Animal animal;
public Container() {}
public static class Animal {
public Animal() {}
public Animal(int age) {
this.age = age;
}
public int age;
}
public static class Bird extends Animal {
public Bird() {}
public Bird(int age) {
super(age);
}
}
}
当用 Bird 序列化 Container 对象然后反序列化它时,它将变成 Animal。
@Test
public void fromBirdToAnimal() throws IOException {
Container one = new Container();
one.animal = new Container.Bird(123);
String json = new ObjectMapper().writeValueAsString(one);
Container two = new ObjectMapper()
.readerFor(Container.class).readValue(json);
assertEquals(123, two.animal.age);
assertEquals(Container.Animal.class, two.animal.getClass());
}
如果容器类是不可能的,但你知道你需要的类(你的继承树的根类),告诉ObjectMapper.readerFor
可以帮助你。
@Test
public void fromBirdToAnimal() throws IOException {
Container.Bird one = new Container.Bird(123);
String json = new ObjectMapper().writeValueAsString(one);
Container.Animal two = new ObjectMapper().readerFor(Container.Animal.class).readValue(json);
assertEquals(123, two.age);
assertEquals(Container.Animal.class, two.getClass());
}