Reputation: 1299
I am using Gson api to convert the object to json document. One of the properties is a string which is a xml string. Upon converting the xml is not printed properly all the newlines are converted to \n and all the tabs are converted to \t.
Code :
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>
Upvotes: 2
Views: 7385
Reputation: 389
So I tried the only answer that was given on this question and it did not work so I had to figure out why. After some experimenting, it turns out a few edits needed to be made, so I created the following little utility method which helped:
private static String serialize(Object object) {
final Gson prettyGson = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.disableHtmlEscaping()
.create();
final String prettyGsonString = prettyGson.toJson(object);
return prettyGsonString
.replaceAll("\\\\n", "\n")
.replaceAll("\\\\t", "\t")
.replaceAll("\\\\b", "\b")
.replaceAll("\\\\r", "\r")
.replaceAll("\\\\f", "\f")
.replaceAll("\\\\'", "\'");
}
Upvotes: 2
Reputation: 39206
This has to be achieved using String replaceAll()
method. The new line character, tab, carriage return etc should be replaced with empty string before the object is converted into JSON.
Gson doesn't have any feature to remove these characters.
1) Replace all
xmlString.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "")
2) Set the xml string value in the object
3) Convert the object to JSON
Edit:-
If you need new line, please use the below which doesn't replace new line "\n".
xmlString.replaceAll("\r", "").replaceAll("\t", "")
Upvotes: 0