1
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(). 对于反序列化,应该使用 to 的值来查找实际对象(Bar,Bar2等)

杰克逊怎么能做到这一点?

4

1 回答 1

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() {
    }
}
于 2017-01-16T09:44:32.627 回答