我正在上一堂像下面这样的课,
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,"name":"Guna","age":25} //Here I want the String with Id, So this is correct
如何制作带有字段 [在某个时刻] 和没有字段 [在某个时刻] 的 JSON 字符串。
任何帮助都将非常感激。
Thanks.
更好的是使用 @expose 注释,例如
public class Student {
public int id;
@Expose
public String name;
@Expose
public int age;
}
并使用下面的方法从您的对象获取 Json 字符串
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);
}
如果 id 列设置为 0,它将忽略 id 列,或者返回带有 id 字段的 json 字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)