Why ObjectNode adds backslash in in Json String

前提是你 提交于 2021-02-11 14:04:41

问题


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:


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);



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/52394853/why-objectnode-adds-backslash-in-in-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!