2014-10-28 30 views
11

我有像以下一類創建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字符串場[在某個點],少了場[在一點]。

任何幫助將非常可觀。

謝謝。

+0

當您聲明一個int變量時,其默認值爲0.一個int不能爲空。因此,我建議您使用字符串代替或忽略ID值,如果它是0. – joao2fast4u 2014-10-28 10:22:32

+0

@ joao2fast4u我編輯了我的代碼朋友 – Gunaseelan 2014-10-28 10:24:39

+0

@Gunaseelan檢查我的答案以獲得更好的解決方案。創建json之後,您無需刪除密鑰。 – 2014-10-28 10:38:55

回答

16

更好的是使用@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字符串,無論是它會返回帶有id字段的json字符串。

+0

是的,我認爲這是更好的答案。謝謝bro – Gunaseelan 2014-10-28 10:40:40

+0

您最歡迎:) – 2014-10-28 10:41:30

3

你可以用gson探索json樹。

嘗試這樣:

gson.toJsonTree(stu1).getAsJsonObject().remove("id"); 

您可以添加一些屬性也:

gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100"); 
1

你有兩個選擇。

  • 使用Java的transient關鍵字來表示不應該序列化一個字段。 Gson會自動排除它。這可能不適合你,因爲你有條件地想要。

  • 使用@expose標註爲您要和初始化GSON建設者如下領域:

所以你需要使用@expose標記姓名和年齡字段,並且您需要有兩個不同的Gson實例用於默認的實例,其中包含所有字段,以及上面的實例不包含@Expose註釋的字段。

2
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(stu2); 
jsObj.remove("age"); // remove field 'age' 
jsObj.addProperty("key", "value"); // add field 'key' 

System.out.println(jsObj); 

你可以把JSONObject

2

操縱你應該引入更多領域Student類,會發現GSONid系列化的政策。 然後,你應該實現自定義序列化器,將實現TypeAdapter。在你的TypeAdapter實現根據ID序列化政策你會序列化或不。那麼你應該在GSON工廠註冊你的TypeAdapter

GsonBuilder gson = new GsonBuilder(); 
gson.registerTypeAdapter(Student.class, new StudentTypeAdapter()); 

希望這會有所幫助。