[英]Unable to understand ObjectMapper writeValueAsString(Object value) method behavior
I am using ObjectMapper
to get value as String
from JsonNode
but see this weird behavior.我正在使用
ObjectMapper
从JsonNode
获取值作为String
但看到这种奇怪的行为。 I am missing something here.我在这里遗漏了一些东西。 Can someone explain why is the Actual result has
double quotes
in it?有人可以解释为什么实际结果中有
double quotes
吗? I expect this test to pass but the assertion fails:我希望这个测试通过,但断言失败:
Unit Test:单元测试:
@Test
public void testGetValueAsString() throws JsonProcessingException {
ObjectMapper fasterXmlMapper = new com.fasterxml.jackson.databind.ObjectMapper();
JsonNode node = new TextNode("{}");
String valueAsString = fasterXmlMapper.writeValueAsString(node);
assertEquals("{}", valueAsString);
}
Test Run Output:试运行 Output:
expected:<[{}]> but was:<["{}"]>
Expected :{}
Actual :"{}"
Here I am referring to following library and classes:在这里,我指的是以下库和类:
I am using jackson-databind-2.9.9.jar
我正在使用
jackson-databind-2.9.9.jar
com.fasterxml.jackson.databind.JsonNode
and com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
and com.fasterxml.jackson.databind.ObjectMapper
According to the documentation a TextNode
is根据文档,
TextNode
是
/** * Value node that contains a text value.
/** * 包含文本值的值节点。 */
*/
So TextNode
wraps its argument in ""
.因此
TextNode
将其参数包装在""
中。 In order to make your test running you either need to chose a different subclass of Node
or adjust the assertion to assertEquals("\"{}\"", valueAsString);
为了使您的测试运行,您要么需要选择不同的
Node
子类,要么将断言调整为assertEquals("\"{}\"", valueAsString);
. .
You can read on json.org that string
is:您可以在json.org上阅读该
string
:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes , using backslash escapes.
字符串是零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义。 A character is represented as a single character string.
字符表示为单个字符串。 A string is very much like a C or Java string.
字符串非常类似于 C 或 Java 字符串。
And this is what com.fasterxml.jackson.databind.node.TextNode
does, wraps {}
in double quotes which gives "{}"
.这就是
com.fasterxml.jackson.databind.node.TextNode
所做的,将{}
用双引号括起来,给出"{}"
。
If you want to have an empty JSON Object
you can create com.fasterxml.jackson.databind.node.ObjectNode
instance: If you want to have an empty
JSON Object
you can create com.fasterxml.jackson.databind.node.ObjectNode
instance:
JsonNode node = mapper.getNodeFactory().objectNode();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.