Using Gson to serialize strings with \n in them

6.1k views Asked by At

\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}
1

There are 1 answers

3
slarge On BEST ANSWER

I am guessing that the gsonOutput has escaped the new line so if you change the line

final String gsonOutput = new Gson().toJson(map);

to (to unescape it):

final String gsonOutput = new Gson().toJson(map).replace("\\n", "\n");

you will get the output

gsonOutput:{"x":"First_Line
Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It"}
toStringOutput:{x=First_Line
Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It}

There probably is a better way of doing this :-)