I would use a library to create your JSON String for you. Some options are:

  • GSON
  • Crockford's lib

This will make dealing with escaping much easier. An example (using org.json) would be:

JSONObject obj = new JSONObject();

obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);

// etc.

final String json = obj.toString(); // <-- JSON string
Answer from jabclab on Stack Overflow
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - The simplest and smallest library in our review is JSON-java also known as org.json. To construct a JSON object, we simply create an instance of JSONObject and basically treat it like a Map: JSONObject jsonObject = new JSONObject(); jsonObject.put("message", "Hello \"World\""); String payload = jsonObject.toString(); This will take the quotes around “World” and escape them:
Discussions

java - How should I escape strings in JSON? - Stack Overflow
There is now a StringEscapeUtils#escapeJson(String) method in the Apache Commons Text library. ... This functionality was initially released as part of Apache Commons Lang version 3.2 but has since been deprecated and moved to Apache Commons Text. So if the method is marked as deprecated in your IDE, you're importing the implementation from the wrong library (both libraries use the same class name: StringEscapeUtils). The implementation isn't pure Json. As per the Javadoc... More on stackoverflow.com
🌐 stackoverflow.com
Escape JSON string in Java - Stack Overflow
And afterwards deserialize that string. GenericJson.toString produces simple JSON, but \n etc. are not escaped: ... I don't want to reinvent the wheel, so I'd like to use Jackson or an existing API, if possible. ... I was trying to avoid writing it from scratch, there's also Apache Commons method to escape JavaScript... More on stackoverflow.com
🌐 stackoverflow.com
How can I prevent my JSON file from being escaped?
because you write a Java String as JSON Object so Jackson needs to escape your Java String into a JSON String remove toPrettyString() and you are good More on reddit.com
🌐 r/SpringBoot
3
4
May 19, 2024
Escape double-quotes in JSON string
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
6
1
September 29, 2021
🌐
FreeFormatter
freeformatter.com › json-escape.html
Free Online JSON Escape / Unescape Tool - FreeFormatter.com
Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing.
🌐
Google Groups
groups.google.com › g › google-web-toolkit › c › 0SpUPTgGNgE
How to unescape a JSONString?
There's no escaping. You have a string value, it stays a string value. If its content is JSON representing an array and you want that array, then indeed you have to parse the JSON. It looks like there's a major misunderstanding about what GWT does with your code, and/or possibly where/when ...
🌐
JSON Formatter
jsonformatter.org › java-escape
Best Java Escape Characters tools to escape sequences and Strings
Escapes or unescapes a Java string removing traces of offending characters that could prevent compiling.
Top answer
1 of 16
190

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

2 of 16
60

Extract From Jettison:

 public static String quote(String string) {
         if (string == null || string.length() == 0) {
             return "\"\"";
         }

         char         c = 0;
         int          i;
         int          len = string.length();
         StringBuilder sb = new StringBuilder(len + 4);
         String       t;

         sb.append('"');
         for (i = 0; i < len; i += 1) {
             c = string.charAt(i);
             switch (c) {
             case '\\':
             case '"':
                 sb.append('\\');
                 sb.append(c);
                 break;
             case '/':
 //                if (b == '<') {
                     sb.append('\\');
 //                }
                 sb.append(c);
                 break;
             case '\b':
                 sb.append("\\b");
                 break;
             case '\t':
                 sb.append("\\t");
                 break;
             case '\n':
                 sb.append("\\n");
                 break;
             case '\f':
                 sb.append("\\f");
                 break;
             case '\r':
                sb.append("\\r");
                break;
             default:
                 if (c < ' ') {
                     t = "000" + Integer.toHexString(c);
                     sb.append("\\u" + t.substring(t.length() - 4));
                 } else {
                     sb.append(c);
                 }
             }
         }
         sb.append('"');
         return sb.toString();
     }
🌐
Tabnine
tabnine.com › home page › code › java › org.json.simple.jsonobject
Java Examples & Tutorials of JSONObject.escape (org.json.simple) | Tabnine
@Override public <T extends Map<String, String>> InitializedBuilder productContext(T productContext) { String json = new JSONObject(productContext).toString(); String transformed; if (isJSON) { transformed = JSONObject.escape(json); } else { StringWriter writer = new StringWriter(); try { JavascriptEncoder.escape(writer, json); transformed = writer.toString(); } catch (IOException e) { // there's no I/O, so there shouldn't be an IOException throw new IllegalStateException(e); } } additionalContext.put("productContextHtml", transformed); return this; } origin: pstehlik/gelf4j ·
🌐
SSOJet
ssojet.com › escaping › json-escaping-in-java
JSON Escaping in Java | Escaping Techniques in Programming
A frequent pitfall involves backslashes. In Java, a literal backslash must be escaped as \\. Therefore, a file path like C:\Users\Name must be transformed into "C:\\Users\\Name" to prevent it from being misinterpreted as an escape sequence within the JSON string.
Find elsewhere
🌐
W3Docs
w3docs.com › java
How should I escape strings in JSON?
To escape these characters in a string, you can use the \\ sequence to escape the backslash, and the \" sequence to escape the double quote. Here is an example of a JSON string with some escaped characters:
🌐
Blogger
javarevisited.blogspot.com › 2017 › 06 › how-to-escape-json-string-in-java-eclipse-IDE.html
How to Escape JSON String in Java- Eclipse IDE Tips and Example
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even ...
🌐
MojoAuth
mojoauth.com › escaping › json-escaping-in-java
JSON Escaping in Java | Escaping Methods in Programming Languages
The Java String class provides methods to handle these characters effectively. To implement JSON escaping in Java, you can use libraries like org.json, Gson, or Jackson for converting Java objects to JSON strings while handling escaping automatically.
Top answer
1 of 2
44

No additional dependencies needed: You're looking for JsonStringEncoder#quoteAsString(String).

Click for JsonStringEncoder javadoc

Example:

import com.fasterxml.jackson.core.io.JsonStringEncoder;

JsonStringEncoder e = JsonStringEncoder.getInstance();
String commands = "ls -laF\\ndu -h";
String encCommands = new String(e.quoteAsString(commands));
String o = "{commands: \"" + encCommands + "\", id: 0, timeout: 0}"

Ref: http://fasterxml.github.io/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/io/JsonStringEncoder.html

2 of 2
5

Using Gson for serialization proved to be quite easy and bulletproof. Afterwards Apache's commons-lang3 = 3.1 escapeEcmaScript is used. In 3.2 there's also escapeJson method.

import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;

public class MyJson extends GenericJson {

    @Key("commands")
    public String commands;

    public String serialize() throws IOException {
      Gson gson = new Gson();
      String g = gson.toJson(this);
      return StringEscapeUtils.escapeEcmaScript(g);
    }
}

This produces escaped JSON:

{\"commands\":\"ls -laF\\ndu -h\"}

Deserialization is then quite simple:

protected MyJson deserialize(String str) throws IOException {
    String json = StringEscapeUtils.unescapeEcmaScript(str);
    JsonObjectParser parser = (new JacksonFactory()).createJsonObjectParser();
    return parser.parseAndClose(new StringReader(json), MyJson.class);
}

The escapeEcmaScript method isn't complicated, it does following replacement:

  {"'", "\\'"},
  {"\"", "\\\""},
  {"\\", "\\\\"},
  {"/", "\\/"}

But at least is something I don't have to care about.

🌐
Example Code
example-code.com › java › json_escape_unescape_string.asp
Java JSON Escape and Unescape a String
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
TutorialsPoint
tutorialspoint.com › json_simple › json_simple_escape_characters.htm
JSON.simple - Escaping Special Characters
import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); String text = "Text with special character /\"\'\b\f\t\r\n."; System.out.println(text); System.out.println("After escaping."); text = jsonObject.escape(text); System.out.println(text); } }
🌐
Crunchify
crunchify.com › json tutorials › escape character utility for url and json data – feel free to use in your java project
Escape Character Utility for URL and JSON data - Feel free to use in your Java Project • Crunchify
November 20, 2021 - Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) // So a tab becomes the characters '\\' and 't'. // The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.
🌐
Reddit
reddit.com › r/springboot › how can i prevent my json file from being escaped?
r/SpringBoot on Reddit: How can I prevent my JSON file from being escaped?
May 19, 2024 -

I am connecting to an external API and pulling down information.

The information is in JSON format and I can pretty print it to the console just fine. But when saving it as a file, it escapes everything. How can I prevent this?

Request request = new Request.Builder()
        .url("https://api.foursquare.com/v3/places/search?categories=19014&near=Athens%2C%20Greece")
        .get()
        .addHeader("accept", "application/json")
        .addHeader("Authorization", System.getenv("foursquare_api_key"))
        .build();

Response response = client.newCall(request).execute();
ObjectMapper mapper = new ObjectMapper();
Object jsonString = mapper.readTree(response.body().string()).toPrettyString();

// This looks just fine
System.out.println(jsonString);

// This escapes the file
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
writer.writeValue(new File("src/main/resources/results/greece.athens.json"), jsonString);

Any ideas what I am doing wrong?

Thanks!

🌐
GitHub
gist.github.com › jjfiv › 2ac5c081e088779f49aa
JSON escaping and unescaping that really works, no dependencies. · GitHub
JSON escaping and unescaping that really works, no dependencies. Raw · JSONUtil.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Testmuai
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON content to escaped HTML.
In Java, you can escape JSON data ... with the special characters replaced by their corresponding escape sequences by using the escape() method....
🌐
Blogger
javarevisited.blogspot.com › 2017 › 06 › how-to-escape-json-string-in-java-eclipse-IDE.html
Javarevisited: How to Escape JSON String in Java- Eclipse IDE Tips and Example
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even ...
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to Escape JSON String in Java - Eclipse IDE Tips - Java Code Geeks
June 27, 2017 - You can escape String in Java by putting a backslash in double quotes e.g.” can be escaped as\” if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quotes with escape character for even ...