String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
        System.out.println(StringEscapeUtils.unescapeJava(test));

This might help you.

Answer from gauti on Stack Overflow
Top answer
1 of 4
28
String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
        System.out.println(StringEscapeUtils.unescapeJava(test));

This might help you.

2 of 4
7

I have not tried Jackson. I just have similar situation.

I used org.apache.commons.text.StringEscapeUtils.unescapeJson but it's not working for malformed JSON format like {\"name\": \"john\"}

So, I used this class. Perfectly working fine.

https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java

// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.utility.json;

public class JSONUtil {
  public static String escape(String input) {
    StringBuilder output = new StringBuilder();

    for(int i=0; i<input.length(); i++) {
      char ch = input.charAt(i);
      int chx = (int) ch;

      // let's not put any nulls in our strings
      assert(chx != 0);

      if(ch == '\n') {
        output.append("\\n");
      } else if(ch == '\t') {
        output.append("\\t");
      } else if(ch == '\r') {
        output.append("\\r");
      } else if(ch == '\\') {
        output.append("\\\\");
      } else if(ch == '"') {
        output.append("\\\"");
      } else if(ch == '\b') {
        output.append("\\b");
      } else if(ch == '\f') {
        output.append("\\f");
      } else if(chx >= 0x10000) {
        assert false : "Java stores as u16, so it should never give us a character that's bigger than 2 bytes. It literally can't.";
      } else if(chx > 127) {
        output.append(String.format("\\u%04x", chx));
      } else {
        output.append(ch);
      }
    }

    return output.toString();
  }

  public static String unescape(String input) {
    StringBuilder builder = new StringBuilder();

    int i = 0;
    while (i < input.length()) {
      char delimiter = input.charAt(i); i++; // consume letter or backslash

      if(delimiter == '\\' && i < input.length()) {

        // consume first after backslash
        char ch = input.charAt(i); i++;

        if(ch == '\\' || ch == '/' || ch == '"' || ch == '\'') {
          builder.append(ch);
        }
        else if(ch == 'n') builder.append('\n');
        else if(ch == 'r') builder.append('\r');
        else if(ch == 't') builder.append('\t');
        else if(ch == 'b') builder.append('\b');
        else if(ch == 'f') builder.append('\f');
        else if(ch == 'u') {

          StringBuilder hex = new StringBuilder();

          // expect 4 digits
          if (i+4 > input.length()) {
            throw new RuntimeException("Not enough unicode digits! ");
          }
          for (char x : input.substring(i, i + 4).toCharArray()) {
            if(!Character.isLetterOrDigit(x)) {
              throw new RuntimeException("Bad character in unicode escape.");
            }
            hex.append(Character.toLowerCase(x));
          }
          i+=4; // consume those four digits.

          int code = Integer.parseInt(hex.toString(), 16);
          builder.append((char) code);
        } else {
          throw new RuntimeException("Illegal escape sequence: \\"+ch);
        }
      } else { // it's not a backslash, or it's the last character.
        builder.append(delimiter);
      }
    }

    return builder.toString();
  }
}
🌐
Google Groups
groups.google.com › g › google-web-toolkit › c › 0SpUPTgGNgE
How to unescape a JSONString?
For my example, I was querying an API for WebRTC ICE servers, which returned a string which was a JSON array. ... private static native JavaScriptObject createPeerConnection(String iceServersJson) /*-{ var peerConnectionConfig = { iceServers: iceServersJson }; return new RTCPeerConnection(peerConnectionConfig); }-*/;
Discussions

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
android - How to unescape JSON/Java with support to ampersand? - Stack Overflow
I would say, this is the upstream ... string. Ideally, it should be fixed so that they don't double escape the characters represented in escaped-unicode format. Then \\u0026 should become \u0026. You can also compose your own AggregateTranslator the way it properly handles this scenario. There might be few options but they could all be error-prone and stop working properly in other scenarios. So, you have to be careful with that. You can also run the unescapeJson method twice ... More on stackoverflow.com
🌐 stackoverflow.com
java - How to unescape json? - Stack Overflow
Assuming you really do have that string, it looks like someone's double-encoded it (that is, serialized a structure to JSON, then serialized that string to JSON a second time). More on stackoverflow.com
🌐 stackoverflow.com
java - How should I escape strings in JSON? - Stack Overflow
The RFC also does not state the character encoding for the whole json string. Some clarification would be much appreciated. Maybe for Java programmers, the term "unicode" is enough to ring a bell, but for C/C++ programmers having a std::string etc, it is not enough information. More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is Unescape JSON?
Unescape JSON is the method of converting JSON strings encoded with specific characters to escape special characters such as newlines, quotes, and then converting back to its original format. In other words, JSON Unescape converts JSON strings to plain JSON, so that you can show text that is contained in 'pre' tags. The escape notation character, in most cases the backslash (), will be unwrapped from any string when the code is parsed. The code may also be pretty printed or minified. In JSON, you need to escape specific characters in order to encode them properly. For example, if a JSON string
🌐
testmu.ai
testmu.ai › home › free tools › json unescape online
Free JSON Unescape Online Tool | TestMu AI.
How does Unescape JSON work?
Unescape JSON removes traces of offending characters that could prevent parsing. To unescape JSON strings, several libraries and tools are available in different programming languages. For example, in Python, the json.loads() can help you to unescape a JSON string and convert it into a Python dictionary and json.dumps() convert the Python object into a JSON string.
🌐
testmu.ai
testmu.ai › home › free tools › json unescape online
Free JSON Unescape Online Tool | TestMu AI.
Difference between JSON Unescapes and Escapes
JSON Unescape is the process of converting back escaped characters in any JSON string back to their original format whereas JSON Escape is the process of converting special characters in any JSON string into their escaped form. Following are the special characters that typically need to be escaped.Backslash, Double-quote, Forward slash. When the above characters are there in a JSON string, they are typically preceded by a backslash character (). This indicates that the characters should be regarded as literal characters rather than special characters in JSON. JSON Unescape takes an escaped JSO
🌐
testmu.ai
testmu.ai › home › free tools › json unescape online
Free JSON Unescape Online Tool | TestMu AI.
🌐
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
🌐
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.
🌐
Testmu
testmu.ai › home › free tools › json unescape online
Free JSON Unescape Online Tool | TestMu AI.
Parsing JSON: To convert JSON strings into Java objects, utilize libraries such as Jackson, GSON, or the built-in JSON support in Java (javax.json). During this operation, escape sequences are automatically translated to their unescaped counterparts.
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - In this short article, we’ve seen how to escape JSON strings in Java using different open source libraries.
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › org.apache.commons.lang3.stringescapeutils
org.apache.commons.lang3.StringEscapeUtils.unescapeJson java code examples | Tabnine
June 27, 2019 - Unescapes any Json literals found in the String. For example, it will turn a sequence of '\' and 'n'into a newline character, unless the '\' is preceded by another '\'. ... Escapes the characters in a String using HTML entities.
🌐
JSON Formatter
jsonformatter.org › java-unescape
Best Java Unescape tools to unescape java code.
Escapes or unescapes a Java string removing traces of offending characters that could prevent compiling.
🌐
Java Guides
javaguides.net › p › json-escape-unescape-online-tool.html
JSON Escape / Unescape Online Tool
August 23, 2023 - Input the escaped JSON string into the text area. Click the "Unescape" button.
🌐
Apache Commons
commons.apache.org › proper › commons-text › javadocs › api-release › org › apache › commons › text › StringEscapeUtils.html
StringEscapeUtils (Apache Commons Text 1.9 API)
The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped. See http://www.ietf.org/rfc/rfc4627.txt for further details. ... Unescapes any Java literals found in the String.
🌐
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!

🌐
Stack Overflow
stackoverflow.com › questions › 76247722 › how-to-unescape-json-java-with-support-to-ampersand
android - How to unescape JSON/Java with support to ampersand? - Stack Overflow
StringEscapeUtils.unescapeJson(input).replace("\\u0026","&").replace("\\/", "/") This works, but I think I should use something more official, as it might fail due to too-direct replacing of substrings. Looking at unescapeJson code (which is the same for Java&Json, it seems), I thought that maybe I could just add the rules: /**based on StringEscapeUtils.unescapeJson, but with addition of 2 more rules*/ fun unescapeUrl(input: String): String { val unescapeJavaMap= hashMapOf<CharSequence, CharSequence>( "\\\\" to "\\", "\\\\" to "\\", "\\\"" to "\"", "\\'" to "'", "\\" to StringUtils.EMPTY, //ad
🌐
JetBrains
youtrack.jetbrains.com › issue › IJPL-65642 › Unescape-when-copying-content-of-JSON-string
Unescape when copying content of JSON string : IJPL-65642
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
YouTube
youtube.com › watch
MuleSoft || How to Unescape JSON String back to its Original Format? - YouTube
This video explains methods of converting the escaped JSON string with junk characters back to its actual JSON format.This could be due to internal conversio...
Published   April 7, 2020
🌐
CodingTechRoom
codingtechroom.com › question › unescape-json-string-java-jackson
How to Unescape a JSON String using Java and Jackson Library - CodingTechRoom
Use the `ObjectMapper` class from the Jackson library to parse and unescape the JSON string. The `readValue` method is effective for converting a JSON string into the corresponding Java object.
🌐
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();
     }