【问题标题】:Using Gson to serialize strings with \n in them使用 Gson 序列化带有 \n 的字符串
【发布时间】:2015-06-09 12:21:13
【问题描述】:
字符串中的

\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 像 toStringOutput 一样显示?
  • @slarge:是的,在下一行打印“Want_This_To_Be_Printed_In_Next_Line”时,希望 gsonOutput 与 toStringOutput 相同。

标签: java serialization gson


【解决方案1】:

我猜 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}

可能有更好的方法来做到这一点:-)

【讨论】:

  • 感谢您的回答。这个解决方案对你有用吗?它对我没有用。调试器显示 gson 实际上已将 \ 和 n 分开,并将它们视为单独的字符。
  • 它对我有用,是的,在发布之前对其进行了测试。您是否在问题中未分享任何代码?
  • @Ameliorator 如果它有效,那么如果你不介意,请接受我的回答:-)
猜你喜欢
  • 2013-01-18
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多