JSON序列化子类到超类

时间:2018-05-16 07:00:10

标签: java json jackson json-deserialization json-serialization

我有两个班级:

超类:

public class A
{
    public int a;

    public A(int a)
    {
        this.a = a;
    }
}

子类:

public class B extends A
{
    public B(int a)
    {
        super(a);
    }
}

我使用Jackson来序列化/反序列化A& A的实例。乙

我希望将B类序列化为A 。我希望这是直截了当的,因为B没有任何成员。 但是我得到了杰克逊的一个例外,我发现的唯一解决方案是将B声明为A的子类型 - 我不想使用这个解决方案,因为这样B被序列化并反序列化为B. / p>

我的限制是我无法创建另一个类来包含A / B(容器)。

1 个答案:

答案 0 :(得分:1)

如果您有容器类,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());
}
相关问题