2016-07-26 93 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();