问题描述
我正在尝试将json放在java中的javascript文件中,但是当我将json写入字符串时,该字符串似乎不是javascript的有效json;它缺少一些逃脱。 (这发生在json中的一个字符串中,我将其格式化为faux 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.)
例如,这将是我的javascript文件中的有效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);
但是当我将它直接写入带有jackson的文件时,我得到了第一个好结果:
But when I write it directly to a file with jackson, I get the first, good result:
new ObjectMapper().writer().writeValue(fileToWriteTo, booksMessage);
那么为什么jackson在写入文件时会有不同的逃避方式,如何让它像写给字符串的时间对我来说?
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?
推荐答案
我添加了
booksJson = Pattern.compile("\\\\").matcher(booksJson).replaceAll("\\\\\\\\");
它会转义所有转义字符。这样当我将它写入文件并删除转义时,我仍然有我需要的转义。事实证明我真正的问题是如何在没有删除Java转义的情况下写入文件。
which escapes all the escape characters. That way when I write it to file and it removes the escapes, I still have the escapes I need. So turns out my real question was how to write to file without Java escapes being removed.
这篇关于杰克逊没有逃脱JSON中的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!