Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson not escaping quotes in JSON

I'm trying to put a json in a javascript file in java, but when I write the json to a string, the string doesn't appear to be a valid json for javascript; it is missing some escapes. (This is happening in a string in the json which I formatted as a faux json.)

For example, this would be a valid json in my javascript file:

{
   "message": 
   "the following books failed: [{\"book\": \"The Horse and his Boy\",\"author\": \"C.S. Lewis\"}, {\"book\": \"The Left Hand of Darkness\",\"author\": \"Ursula K. le Guin\"}, ]"
}

Here's what I get, though, where the double quotes aren't escaped:

{
   "message": 
   "The following books failed: [{"book": "The Horse and his Boy","author": "C.S. Lewis"}, {"book": "The Left Hand of Darkness","author": "Ursula K. le Guin"}, ]"
}

I get the second result when I do this:

new ObjectMapper().writer().writeValueAsString(booksMessage);

But when I write it directly to a file with jackson, I get the first, good result:

new ObjectMapper().writer().writeValue(fileToWriteTo, booksMessage);

So why does jackson escape differently when writing to a file, and how do I get it to escape like that for me when writing to a string?

like image 534
CorayThan Avatar asked Nov 09 '13 00:11

CorayThan


People also ask

How do you escape a quote in JSON?

If you're making a . json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes: \" is the one you're looking for.

How do I add an escape character to a JSON string in Java?

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 a medium-size JSON is time taking, boring, and error-prone.

How do I remove an escape character from a JSON string in Java?

String jsonFormattedString = jsonStr. replaceAll("\\", "");


1 Answers

The writeValue() methods of the ObjectWriter class encode the input text.

You don't need to write to a file. An alternative approach for getting the same string could be:

StringWriter sw = new StringWriter();
new ObjectMapper().writer().writeValue(sw, booksMessage);
String result = sw.toString();
like image 72
PNS Avatar answered Sep 18 '22 05:09

PNS