1

I am a newbie to Gson library, not sure why this object to json converter works weird. I have code something similar to the below

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));

   }
 }

I want the output to be something like this

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

but I get the output

{
 "name":'Point'
 }

My subclass variables are not serialized properly.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Subha
  • 59
  • 7

1 Answers1

0

You need annotate your class with expose, just for field to be exposed. So do you need erase expose before private int x;.

To supress a field it is necessary to instantiate a Gson with a excludeFieldsWithoutExposeAnnotation modifier.

GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
John F. Miller
  • 26,961
  • 10
  • 71
  • 121
Assuiti
  • 1
  • 1