\n in a string is effective in printing the text following \n in next line. However, if the same string is serialized using Gson, then \n is no more effective in printing it in next line. How can we fix this ? Sample program given below.
In the program below, output of toString on map is printing text in next line due to presence of \n. However, the json string serialized using Gson is not able to show the same behaviour. In serialized string i.e. gsonOutput variable, '\' and 'n' are getting treated as separate characters, due to which the text after \n is not getting printed in next line. How can we fix this in gson serialization ?
Program:
Map<String, String> map = new HashMap<String,String>();
map.put("x", "First_Line\nWant_This_To_Be_Printed_In_Next_Line");
final String gsonOutput = new Gson().toJson(map);
final String toStringOutput = map.toString();
System.out.println("gsonOutput:" + gsonOutput);
System.out.println("toStringOutput:" + toStringOutput);
Output:
gsonOutput:{"x":"First_Line\nWant_This_To_Be_Printed_In_Next_Line"}
toStringOutput:{x=First_Line
Want_This_To_Be_Printed_In_Next_Line}
I am guessing that the gsonOutput has escaped the new line so if you change the line
to (to unescape it):
you will get the output
There probably is a better way of doing this :-)