49
    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}

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

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

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

Is GSON going mad or is it something that I am doing wrong? What is happening to with Back Slashes and from where does this u003d appears? 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.

Fahad Ishaque
  • 1,916
  • 1
  • 17
  • 21

2 Answers2

129

The = sign is encoded to \u003d. Hence you need to use 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("\\\\", "\\");
Pang
  • 9,564
  • 146
  • 81
  • 122
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
3

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:

Gson gson = new Gson();
String json = (gson.toJson(data)).replaceAll("\\\\n", "\\n");
Nicholas P.
  • 353
  • 4
  • 14
  • But this is not an answer to the original question, as far as I can see. – anothernode May 16 '18 at 15:22
  • 4
    @anothernode I couldn't add a response to that guy under the question when lower than 50 rep points... So I added another response here, sue me. – Nicholas P. May 17 '18 at 15:50
  • 1
    Look, I was just giving you a friendly hint. No need to be offended. And copying and pasting someone else's answer into your non-answer doesn't make the situation much better. – anothernode May 17 '18 at 16:14