【发布时间】:2023-03-16 01:39:01
【问题描述】:
我正在上课,
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
所以这里我想要类似字符串
{"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 字符串,而没有字段 [在某些时候]。
任何帮助都将不胜感激。
谢谢。
【问题讨论】:
-
声明int变量时,默认值为0。int不能为null。所以我建议你改用 String 或者忽略 id 值,如果它是 0。
-
@joao2fast4u 我已经编辑了我的代码朋友
-
@Gunaseelan 检查我的答案以获得更好的解决方案。创建 json 后无需删除密钥。