How to avoid Jackson escaping double quotes in Java?

Tags: , , ,



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:

Why ObjectNode adds backslash in in Json String

Jackson adds backslash in json

Answer

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.



Source: stackoverflow