0

Here is how I am trying to convert an object to json String

    ObjectNode batch = OBJECT_MAPPER.createObjectNode();
    String s = OBJECT_MAPPER.writeValueAsString((triggerCommands.getCommands()));
    batch.put("commands", s);
    System.out.println("raw String= " + s);
    System.out.println("ObjectNode String = " + batch);

Which results in output of;

raw String= [{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]

ObjectNode String = {"commands":"[{\"cmdid\":\"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b\",\"type\":\"test\"}]"}

I am curious to know why the String gets backslash when I add it into as value of ObjectNode. All i want is

ObjectNode String = {"commands":[{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]}

There is a similar question asked here but has no solid answer that worked.

Anum Sheraz
  • 2,383
  • 1
  • 29
  • 54
  • 2
    Because a in JSON string, double quotes must be escaped. You want to value of the commands property to be a JSON array, not a string. – JB Nizet Sep 18 '18 at 21:39

3 Answers3

2

Since you're working in the JsonNode domain, you want Jackson to convert your commands to a JsonNode, not a String. Like this:

ObjectNode batch = OBJECT_MAPPER.createObjectNode();
JsonNode commands = OBJECT_MAPPER.valueToTree(triggerCommands.getCommands());
batch.set("commands", commands);
dnault
  • 8,340
  • 1
  • 34
  • 53
0

I just read some sourcecodes toString() method of ObjectNode class, calls a TextNode.appendQuoted then a static method CharTypes.appendQuoted(StringBuilder sb, String content), this adds the ( " ) when the object is writed by toString(), here.. when is found a char " then it adds a backlash. Since your key(s) is a Object array, if you check ObjectNode.put implementation its doesn't allow you add a key as array so.. it need to be parsed to a String

Note you wont get this.

ObjectNode String = {"commands":[{"cmdid":"a06c00d4-5b8b-4313-a8f3-5663dde0fa5b","type":"test"}]}

because the key it's not with between a " (quotes) and as a I told ObjectNode doesn't allow you a key of type array.

0
private String writeUnicodeString() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("field1", "Hello World");
    return node.toString();
}
This outputs:

{"field1":"Hello World"}
Nilam
  • 1