JSON, replace quotes and slashes, but by what?

后端 未结 4 795
礼貌的吻别
礼貌的吻别 2021-01-19 18:49

I have the ungrateful task to build a JSON String in Java, manually, without any framework, just a StringBuilder. I know this is bad, but it is only part of a prototype, I w

4条回答
  •  被撕碎了的回忆
    2021-01-19 19:06

    If you want to include a literal double quote in a JSON string, you must escape it by preceding it with a backslash \. So your JSON string would have to look like this:

    {"key" : " \"Some text WITH quotes\" "}
    

    See json.org for the official JSON syntax.

    The forward slash / is not a special character and does not need to be escaped. The backslash \ needs to be escaped with itself: \\.

    Beware that in Java source code the \ is also the escape character and " also needs to be escaped, which means that if you use these as a literals in your source code you must escape them again.

    StringBuilder sb = new StringBuilder();
    sb.append("{\"key\" : \" \\\"Some text WITH quotes\\\" \"");
    

提交回复
热议问题