[英]GSon not serializing properly with inheritance
我是Gson庫的新手,不確定為什么將這個對象轉換為json轉換器會很奇怪。 我有類似下面的代碼
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'
}
我的子類變量未正確序列化。
您需要使用公開注釋類,僅用於公開字段。 因此,您是否需要在private int x;
之前進行擦除暴露private int x;
。
要抑制字段,必須使用excludeFieldsWithoutExposeAnnotation
修飾符實例化Gson。
GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.