我正在下课,
public class Student { public int id; public String name; public int age; }
现在我想创建新的学生,
//while create new student Student stu = new Student(); stu.age = 25; stu.name = "Guna"; System.out.println(new Gson().toJson(stu));
这给我以下输出,
{"id":0,"name":"Guna","age":25} //Here I want string without id,So this is wrong
所以这里我想要String
{"name":"Guna","age":25}
如果我想编辑老学生
//While edit old student Student stu2 = new Student(); stu2.id = 1002; stu2.age = 25; stu2.name = "Guna"; System.out.println(new Gson().toJson(stu2));
现在的输出是
{"id":1002,"age":25} //Here I want the String with Id,So this is correct
如何使用一个字段[某些时候]创建JSON字符串,没有字段[在某个时间点].
任何帮助将是非常可观的.
谢谢.
解决方法
更好的是使用@expose注释
public class Student { public int id; @Expose public String name; @Expose public int age; }
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); }
如果设置为0,它将忽略id列,否则将返回带有字段的json字符串.