Currently, I am facing an issue with formatting a JSON in a JavaScript file using Java. When I convert the JSON to a string, it does not seem to be valid for JavaScript as some escapes are missing. This mainly occurs within a string that I have structured as faux JSON.
For instance, consider the following as 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\"}, ]"
}
On the other hand, here's what I end up with where the double quotes are not properly 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"}, ]"
}
The undesired result is obtained when I use the following code:
new ObjectMapper().writer().writeValueAsString(booksMessage);
However, when I directly write it to a file with Jackson, I get the desired output:
new ObjectMapper().writer().writeValue(fileToWriteTo, booksMessage);
Therefore, I am curious why Jackson behaves differently in escaping characters while writing to a file and how can I achieve the same escape method when writing to a string?