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 should introduce additional field to Student
class that will notice GSON
about id
serialization policy.
Then, you should implement custom serializer that will implement TypeAdapter
. In your TypeAdapter
implementation according to id serialization policy you will serialize it or not. Then you should register your TypeAdapter
in GSON factory:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Student.class, new StudentTypeAdapter());
Hope this helps.
You can explore the json tree with gson.
Try something like this :
gson.toJsonTree(stu1).getAsJsonObject().remove("id");
You can add some properties also :
gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100");
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.
Better is to use @expose annotation like
public class Student {
public int id;
@Expose
public String name;
@Expose
public int age;
}
And use below method to get Json string from your object
private String getJsonString(Student student) {
// Before converting to GSON check value of id
Gson gson = null;
if (student.id == 0) {
gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
} else {
gson = new Gson();
}
return gson.toJson(student);
}
It will ignore id column if that is set to 0, either it will return json string with id field.
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(stu2);
jsObj.remove("age"); // remove field 'age'
jsObj.addProperty("key", "value"); // add field 'key'
System.out.println(jsObj);
You can manipulate with JsonObject