使用 Gson 序列化其中包含 \n 的字符串

Using Gson to serialize strings with \n in them

\n 在字符串中有效地在下一行打印 \n 之后的文本。但是,如果使用 Gson 序列化相同的字符串,则 \n 在下一行打印它时不再有效。我们如何解决这个问题?下面给出了示例程序。

在下面的程序中,由于 \n 的存在,toString 在地图上的输出是在下一行打印文本。但是,使用 Gson 序列化的 json 字符串无法显示相同的行为。在序列化字符串中,即 gsonOutput 变量,'\' 和 'n' 被视为单独的字符,因此 \n 之后的文本不会在下一行打印。我们如何在 gson 序列化中解决这个问题?

节目:

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}

我猜 gsonOutput 已经转义了新行,所以如果你改变行

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

到(取消转义):

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

你会得到输出

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}

可能有更好的方法:-)