Java 字符串的 GSON 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16558709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:24:42  来源:igfitidea点击:

GSON issue with String

javagsonlinkedhashmap

提问by Fahad Ishaque

    String s = "m\"+"/m\/m/m/m/m/m";

    LinkedHashMap<String, String> hm = new LinkedHashMap<>();

    hm.put("test", s);

    System.out.println(hm+"  Hash map = "+hm.toString());

Fine Output is {test=m\/m\/m/m/m/m/m} Hash map = {test=m\/m\/m/m/m/m/m}

精细输出是 {test=m\/m\/m/m/m/m/m} Hash map = {test=m\/m\/m/m/m/m/m}

    String s2 = new Gson().toJson(hm.toString());

    System.out.println("Json result is "+s2);

Not FineOutput is Json result is "{test\u003dm\\/m\\/m/m/m/m/m}"

Not Fine输出是Json result is "{test\u003dm\\/m\\/m/m/m/m/m}"

Is GSONgoing mad or is it something that I am doing wrong? What is happening to with Back Slashesand from where does this u003dappears? I knew that there exists a bug of this nature a long time ago but it was resolved. How can I resolve this issue? Thanks in advance.

GSON要疯了或者是它的东西,我做错了什么?反斜杠发生了什么,它从哪里u003d出现?我很久以前就知道存在这种性质的错误,但已解决。我该如何解决这个问题?提前致谢。

采纳答案by NINCOMPOOP

The =sign is encoded to \u003d.Hence you need to use disableHtmlEscaping().

=标志编码为\u003d.因此你需要使用disableHtmlEscaping()

You can use

您可以使用

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s2 = gson.toJson(hm.toString());

For \/turning into \\/issue, the solution is

对于\/变成\\/问题,解决方案是

s2.replace("\\", "\");

回答by Nicholas Panella

Since some people like to nitpick, I'll add the answer to the question (even though it was already answered and chosen as the correct answer) ...

由于有些人喜欢吹毛求疵,我将添加问题的答案(即使它已经被回答并被选为正确答案)......

I agree with the chose answer to this question, use the following code:

我同意这个问题的选择答案,使用以下代码:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s2 = gson.toJson(hm.toString());
s2.replace("\\", "\");

@Bajrang Hudda has asked about \n ... I hit this issue recently ... I was able to solve it using:

@Bajrang Hudda 询问了 \n ......我最近遇到了这个问题......我能够使用以下方法解决它:

Gson gson = new Gson();
String json = (gson.toJson(data)).replaceAll("\\n", "\n");