2015-10-06 103 views
1

是否可以在不使用Gson序列化的情況下更改Json屬性的名稱?例如,鑑於此JSONJava:Gson更改不帶序列化的屬性名稱

{ 
    "1": { 
     ... 
    }, 
    "2": { 
     ... 
    } 
} 

我可以改變"1""3"而不刪除其內容。我知道addProperty方法添加了一個新屬性,或者用新值覆蓋了一個現有屬性,但我想更改屬性的名稱而不影響其值。另外,粘貼現有值作爲addProperty的第二個參數是不夠的。

編輯:要添加更多的上下文,我將解釋更大的圖片。我有一個長達幾千行的JSON字符串。我正在編寫一個利用Gson的程序,以便更改該JSON字符串中的值。我處於不僅要改變屬性值而且要改變屬性名稱的地步。我已經完成了一切,沒有序列化。

這裏是Java的一個片斷,我寫:

String file = "\\temp.json"; 

FileReader reader = new FileReader(file); 

JsonStreamParser parser = new JsonStreamParser(reader); 
// Parse entire JSON 
JsonElement element = parser.next(); 
// Get root element 
JsonObject sites = element.getAsJsonObject(); 
// Get first child element 
JsonObject site1 = sites.getAsJsonObject("1"); 

JsonObject clust1 = site1.getAsJsonObject("CLUST"); 

for(int i = 1; i < 12; i++) { 
    // "Dynamic" variable   
    String num = Integer.toString(i); 
    // Get property whose name is a number, has siblings 
    JsonObject one = custCluster1.getAsJsonObject(num); 

    one.getAsJsonObject().addProperty("name", "cluster" + i); 

    JsonObject subOne = one.getAsJsonObject("SUB"); 

    subOne.getAsJsonObject().addProperty("name", "aName" + i); 

    for(int n = 1; n < 1002; n++) { 
     // "Dynamic" variable 
     String inst = Integer.toString(n); 
     // Get property whose name is a number, has siblings 
     JsonObject subSub = subOne.getAsJsonObject(inst); 
     // If the property doesn't exist, then don't execute 
     if(subSub != null) { 

      JsonArray subSubArray = subSub.getAsJsonArray("SUBSUB"); 

      subSub.getAsJsonObject().remove("name"); 

      int m = 0; 

      while(m < subSubArray.size()) { 

       subSubArray.get(m).getAsJsonObject().remove("SR"); 

       subSubArray.get(m).getAsJsonObject().remove("FI"); 

       subSubArray.get(m).getAsJsonObject().remove("IND"); 

       subSubArray.get(m).getAsJsonObject().addProperty("ST", "1"); 

       subSubArray.get(m).getAsJsonObject().addProperty("ID", "2"); 

       subSubArray.get(m).getAsJsonObject().addProperty("DESCR", "hi"); 

       m++; 
      } 
      m = 0; 
     } 
    } 
} 
+0

這需要更加具體。除了「你只是改變它」之外,我很難得出答案。你在哪裏閱讀/識別你想改變的這個「1」?無論何時何地,只要您識別該節點,您就可以使用Gson更改它,就像您在其他節點的代碼片段中一樣? **編輯**我看,你只是想改變名稱,但'Gson' API似乎不支持這一行動。是對的嗎? – mmcrae

+0

http://stackoverflow.com/questions/12619991/changing-names-of-properties-while-serializing-to-json-without-source-code可能會幫助 – mmcrae

+0

@mmcrae是的,這是正確的。我會檢查一下。 – UltraSonja

回答

2

感謝@mmcrae幫助和建議這種方法。

由於我已經將(鍵,值)對保存在變量中,因此可以從父級中刪除想要更改其名稱的屬性,然後使用新名稱和已添加的內容添加它保存。

像這樣:

JsonObject sites = element.getAsJsonObject(); 

JsonObject site1 = sites.getAsJsonObject("1"); 

JsonObject clust1 = site1.getAsJsonObject("CLUST"); 

site1.remove("CLUST"); 

site1.add("NEWCLUST", clust1); 
+0

你也可以接受這個答案。祝賀另外一個問題得到解決! – mmcrae