Java – create JSON strings using gson
•
Java
I'm finishing class,
public class Student {
public int id;
public String name;
public int age;
}
Now I want to create a 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
{"name":"Guna","age":25}
If I want to edit old students
//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,"age":25} //Here I want the String with Id,So this is correct
How to use a field [at some time] to create a JSON string without a field [at a certain point in time]
Any help will be very considerable
thank you.
Solution
Better yet, use the @ expose annotation
public class Student {
public int id;
@Expose
public String name;
@Expose
public int age;
}
And get the JSON string from the object using the following method
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);
}
If set to 0, it ignores the ID column, otherwise it returns a JSON string with fields
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
