2016-11-15 420 views
0

我正在使用Gson api將對象轉換爲json文檔。其中一個屬性是一個字符串,它是一個xml字符串。在轉換xml不能正確打印時,所有新行將轉換爲\ n,並將所有制錶轉換爲\ t。如何忽略使用Gson轉換爲字符的換行符

代碼:

Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); 

mashalledJson = gson.toJson(documentPropertiesWrapper); 


expected Output : 

<name>InterestRates_Trade_EMEA_MUREX_OfficialEOD_CentreState</name> 
<snapshotDate>2015-01-01</snapshotDate> 

Actual Output : 

<name>InterestRates_Trade_EMEA_MUREX_OfficialEOD_CentreState</name>\r\n\t<snapshotDate>2015-01-01</snapshotDate> 

回答

0

這已經使用字符串replaceAll()方法來實現。在將對象轉換爲JSON之前,應將新行字符,製表符,回車等替換爲空字符串。

Gson沒有任何功能來刪除這些字符。

1)更換所有

xmlString.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "") 

2)在對象

3)將對象轉換爲JSON

編輯設置XML字符串值: -

如果您需要換新線,請使用下列不替換新線「\ n」。

xmlString.replaceAll("\r", "").replaceAll("\t", "") 
+0

我嘗試了上述,但它仍然不是我所期待的。這一變化後輸出變得像這樣 InterestRates_Trade_EMEA_MUREX_OfficialEOD_CentreState 2015年1月1日 我想snapshotdate來對下一行 –

+0

如果需要新的生產線,請不要更換\ n用「」即只需刪除第二個replaceAll並嘗試。 – notionquest