Jackson:基于已实现的接口的对象标识序列化/反序列化

时间:2017-01-16 08:06:19

标签: java jackson jackson2

interface Foo
  public String key()

class Bar implements Foo
  public int id;
  public String name;
  public Bar2 bar2;  <--- bar2.key() should be used as json value
  String key() { return name }

class Bar2 implements Foo
  public int id;
  public int name;
  public Bar bar;  <--- bar.key() should be used as json value
  String key() { return name }

每当序列化中引用任何类型Foo的对象时,它的值应为object.key()。 对于反序列化,应使用值来查找实际对象(BarBar2等)

杰克逊怎么办呢?

1 个答案:

答案 0 :(得分:0)

你需要一个公共财产的getter方法。将Foo更改为抽象类,并在那里定义属性和getter方法。

public abstract class Foo implements Serializable{
    public String name;
    public Foo bar;

    public Foo() {
    }

    public String getBar(){
        return bar.name;
    }

    public void setBar(Foo bar) {
        this.bar = bar;
    }
}

class Bar extends Foo{
    public int id;

    public Bar() {
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Bar bar = new Bar();
        Bar2 bar2 = new Bar2();
        bar.id = 1; bar.name = "bar1";bar.setBar(bar2);
        bar2.id = 2; bar2.name = "bar2"; bar2.setBar(bar);

        System.out.println(mapper.writeValueAsString(bar));
    }
}

public class Bar2 extends Foo {
    public int id;

    public Bar2() {
    }
}