简体   繁体   English

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

[英]Jackson: Object identity serializaton/deserialization based on implemented interface

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 }

Whenever any object of type Foo is referenced in serialization, it's value should be object.key() . 每当序列化中引用任何类型为Foo对象时,它的值应为object.key() For deserialization, the value to should be used to lookup the actual object ( Bar , Bar2 , etc) 对于反序列化,应该使用值来查找实际对象( BarBar2等)

How can this be done with Jackson? 杰克逊怎么办呢?

you need a getter method for the common property. 你需要一个公共财产的getter方法。 Change Foo into abstract class and define the property and getter method there. 将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() {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM