I am having a class like following,
public class Student {
public int id;
public String name;
public int age;
}
Now I want to c
You have two options.
Use Java's transient keyword which is to indicate that a field should not be serialized. Gson will exclude it automatically. This may not work for you as you want it conditionally.
Use @Expose annotation for the fields that you want and initialize your Gson builder as following:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
So you need to mark name and age fields using @Expose and you need to have two different Gson instances for the default one which includes all fields and the one above which excludes fields without @Expose
annotation.