3

Trying to find a way to stringify a JSON string, with escape characters like JavaScript.

For example --

Input:

{"name":"Error","message":"hello"}

Output:

"{\"name\":\"Error\",\"message\":\"hello\"}"

I am able to get the object as JSON String using Gson, but not stringify (with escape characters).

Is this possible with Java?

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
kn_pavan
  • 1,147
  • 3
  • 15
  • 34
  • 1
    ``strJson.replace("\"","\\\"");`` ? – f1sh May 16 '17 at 11:41
  • 3
    https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html#escapeJson-java.lang.String- – Robin Topper May 16 '17 at 11:42
  • @RobinTopper That's close to what I am looking for. But Jackson's JsonStringEncoder.quoteAsString() feels like a better alternative for me, as it can correct formatting of JSON as well. – kn_pavan May 16 '17 at 17:41
  • Jackson's JsonStringEncoder.quoteAsString() Example: http://stackoverflow.com/a/40430760/639107 – kn_pavan May 16 '17 at 17:43

3 Answers3

5

Your input is a JSON object as text, presumably stored in a String. You're essentially trying to convert that text to a JSON string. So do just that.

String input = "{\"name\":\"Error\",\"message\":\"hello\"}";
System.out.println("Original JSON content: " + input);
Gson gson = new Gson();
String jsonified = gson.toJson(input);
System.out.println("JSONified: " + jsonified);

Since quotes (and other characters) must be escaped in JSON strings, the toJson will properly perform that transformation.

The code above will produce the

Original JSON content: {"name":"Error","message":"hello"}
JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"

In other words, jsonified now contains the content of a JSON string.

With Jackson, the process is the same, just serialize the String instance that contains your JSON object text

ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, input);
jsonified = writer.toString();
System.out.println("JSONified: " + jsonified);

produces

JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"
Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
1

Another solution, I noted in comments:

Jackson's JsonStringEncoder.quoteAsString() Example: stackoverflow.com/a/40430760/639107

kn_pavan
  • 1,147
  • 3
  • 15
  • 34
0

You can try this on your output json string :

String strWithEscChar = output.replaceAll("\"", "\\\\\"");
Yan.F
  • 630
  • 5
  • 19