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.

1
  • 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. Commented Sep 18, 2018 at 21:39

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-1
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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.