英文:
How to avoid Jackson escaping double quotes in Java?
问题
{
"identifierVal": "1234",
"version": "two",
"namesList": [
"test"
]
}
When using Jackson's ObjectMapper
to create a JSON string, you can achieve the expected result by directly constructing the JSON structure using Java objects without manually converting them to strings. This way, Jackson will handle the proper serialization for you, and you won't encounter issues with escaping double quotes or unnecessary backslashes.
英文:
I am working on a project and wanted to rewrite some code written in Gson to Jackson using ObjectMapper. So I am trying to create a JSON string using some properties as below:
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objNode= objectMapper.createObjectNode();
objNode.put("identifierVal", UUID.randomUUID().toString());
objNode.put("version", "two");
List<String> namesList= new ArrayList<>();
namesList.add("test");
objNode.put("namesList", namesList.toString());
String requestObject = objectMapper.writeValueAsString(objNode.toString());
Expected result:
{
"identifierVal":1234,
"version":"two",
"namesList":[
"test"
]
}
Actual:
"{
"\identifierVal\": 1234,
"\version\":"\two\",
"\namesList\": ["\test\"]
}"
So once I create a JSON String using Jackson, it turns out it is escaping double quotes for field names and values and adding a \
at leading and trailing spaces. So service call fails due to the escaping.
I have went through some documentation and I can understand Jackson is escaping double quotes. But is there a way to avoid escaping double quotes and adding of leading and trailing double quotes.
Any help is appreciated. BTW, I followed the links below:
https://stackoverflow.com/questions/52394853/why-objectnode-adds-backslash-in-in-json-string
https://stackoverflow.com/questions/41815818/jackson-adds-backslash-in-json/41816988
答案1
得分: 7
问题在于你在将JSON对象通过其toString()
方法转换为字符串之后再将其传递给objectMapper
。将这段代码:
String requestObject = objectMapper.writeValueAsString(objNode.toString());
修改为:
String requestObject = objectMapper.writeValueAsString(objNode);
你还需要将这段代码进行修改:
List<String> namesList = new ArrayList<>();
namesList.add("test");
objNode.put("namesList", namesList.toString());
修改为:
ArrayNode namesNode = objNode.arrayNode();
namesNode.add("test");
objNode.set("namesList", namesNode);
这样就能按你的期望工作了。
英文:
The problem is you are converting your JSON object to a String via its toString()
method before passing it to the objectMapper
. Change this:
String requestObject = objectMapper.writeValueAsString(objNode.toString());
to this:
String requestObject = objectMapper.writeValueAsString(objNode);
You also need to change this:
List<String> namesList= new ArrayList<>();
namesList.add("test");
objNode.put("namesList", namesList.toString());
to this:
ArrayNode namesNode = objNode.arrayNode();
namesNode.add("test");
objNode.set("namesList", namesNode);
and it will work as you expect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论