我有像以下一類創建JSON字符串,使用GSON
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不能爲空。因此,我建議您使用字符串代替或忽略ID值,如果它是0. – joao2fast4u 2014-10-28 10:22:32
@ joao2fast4u我編輯了我的代碼朋友 – Gunaseelan 2014-10-28 10:24:39
@Gunaseelan檢查我的答案以獲得更好的解決方案。創建json之後,您無需刪除密鑰。 – 2014-10-28 10:38:55