2017-01-16 76 views
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類型的任何對象序列化被引用對象標識serializaton /反序列化,它的值應該是object.key()。 反序列化,以應使用的值來查找實際的對象(BarBar2等)傑克遜:基於實現的接口

這怎麼能與傑克遜做什麼?

回答

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() { 
    } 
}