1

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

Brooklyn99
  • 987
  • 13
  • 24

1 Answers1

7

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.

David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • Thanks for posting the solution. Anyway after I update the code still it is failing because the json now looks like this:: ```{ "identifierVal":1234, "version":"two","namesList":"[ test ]"} ``` . TO be concise. double quotes were wrapped around `[]` instead of actual string `test`. – Brooklyn99 Oct 22 '20 at 21:51
  • @SantosshKumhar That's because you have another inappropriate `toString()` on your list. You didn't add a List to your node, you added a String. – David Conrad Oct 22 '20 at 23:28
  • How can I add list to namesNode.add();? or do you mean to add each item of list to arrayNode? – Brooklyn99 Oct 23 '20 at 03:03
  • 1
    got it. I added each item of list to the arrayNode. Thanks for your help!! – Brooklyn99 Oct 23 '20 at 03:12