为什么ObjectNode在Json String中添加反斜杠 [英] Why ObjectNode adds backslash in in Json String

查看:103
本文介绍了为什么ObjectNode在Json String中添加反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试将对象转换为json字符串的方式

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

哪个输出;

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

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

我很好奇,当我将String添加为ObjectNode的值时,为什么会得到反斜杠.我只想要

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.

推荐答案

由于您在JsonNode域中工作,因此您希望Jackson将您的命令转换为JsonNode,而不是String.像这样:

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

这篇关于为什么ObjectNode在Json String中添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆