如何避免Jackson在Java中转义双引号? [英] How to avoid Jackson escaping double quotes in Java?
问题描述
我正在一个项目上,想使用ObjectMapper重写一些用Gson编写的代码给Jackson.因此,我尝试使用以下一些属性来创建JSON字符串:
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());
预期结果:
{
"identifierVal":1234,
"version":"two",
"namesList":[
"test"
]
}
实际:
"{
"\identifierVal\": 1234,
"\version\":"\two\",
"\namesList\": ["\test\"]
}"
因此,一旦我使用杰克逊(Jackson)创建了JSON字符串,事实证明它是在转义字段名称和值的双引号,并在前导和尾随空格处添加\
.因此,由于转义,服务呼叫失败.
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:
推荐答案
问题是您正在将JSON对象通过其toString()
方法转换为字符串,然后再将其传递给objectMapper
.更改此:
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());
对此:
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);
它会按预期工作.
这篇关于如何避免Jackson在Java中转义双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!