2016-07-26 95 views
0

我是Gson庫的新手,不知道爲什麼這個對象到JSON轉換器的工作原理奇怪。我有類似下面GSon沒有繼承序列化正確

public class A implements Serializable{ 
    @Expose 
    private String name; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

public class B extends A implements Serializable{ 
    @Expose 
    private int x; 

    public int getX() { 
     return x; 
    } 

    public void setX(int x) { 
     this.x = x; 
    } 
} 

public class MainclassTester{ 
    public static void main(String[] args){ 
    public B b = new B(); 
    b.setName("Point"); 
    b.setX(2); 
    final Gson gson = new GsonBuilder().create(); 
    System.out.println(gson.toJson(b)); 

    } 
} 

我想要的輸出碼的東西是這樣的

{ 
"name":'Point', 
"x":2 
} 

,但我得到的輸出

{ 
"name":'Point' 
} 

我的子類變量沒有被正確序列化。

+0

檢查了這一點http://stackoverflow.com/questions/19588020/gson-serialize-a-list-of-polymorphic-objects/22081826#22081826 –

+0

您正在使用哪個版本:??? wih gson 2.7工作正常! –

+0

試過2.6.2並且工作正常,順便說一句,你不要在一個方法中使用'public'作爲變量:'public B b = new B();' – shizhz

回答

0

你需要用暴露的類來註釋你的類,只是爲了暴露域。 那麼你需要在private int x;之前擦除曝光。

要壓縮一個字段,有必要使用excludeFieldsWithoutExposeAnnotation修飾符實例化一個Gson。

GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();