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()
。
对于反序列化,应使用值来查找实际对象(Bar
,Bar2
等)
杰克逊怎么办呢?
答案 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() {
}
}