I am having a class like following,
public class Student {
public int id;
public String name;
public int age;
}
Now I want to create new Student,
//while create new student
Student stu = new Student();
stu.age = 25;
stu.name = "Guna";
System.out.println(new Gson().toJson(stu));
This gives me the following output,
{"id":0,"name":"Guna","age":25} //Here I want string without id, So this is wrong
So here I want String like
{"name":"Guna","age":25}
If I want to edit old Student
//While edit old student
Student stu2 = new Student();
stu2.id = 1002;
stu2.age = 25;
stu2.name = "Guna";
System.out.println(new Gson().toJson(stu2));
Now the output is
{"id":1002,"name":"Guna","age":25} //Here I want the String with Id, So this is correct
How can I make a JSON String with a field [At some point], without a field [at some point].
Any help will be highly appreciable.
Thanks.
There are the following three libraries are used to convert String to JSON Object in Java: Using Gson Library. Using JSON-Simple Library. Jackson Library.
The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With