When using Jackson, System.out.println(new ObjectMapper().readTree(jsonStringObject)); prints the JSON with random spaces in between keys and values

自古美人都是妖i 提交于 2021-02-17 05:15:32

问题


A very strange behavior. When I just print the System.out.println(jsonStringObject); it prints the JSON properly and well, but when I use Jackson's API, namely new ObjectMapper().readTree(jsonStringObject);it incorporates some random spaces.


回答1:


A very strange behavior.

Indeed. But see what the JsonNode class documentation says about the toString() method:

Method that will produce developer-readable representation of the node; which may or may not be as valid JSON. If you want valid JSON output (or output formatted using one of other Jackson supported data formats) make sure to use ObjectMapper or ObjectWriter to serialize an instance, for example:

String json = objectMapper.writeValueAsString(rootNode);



回答2:


You should try to use the ObjectMapper directly to deserialize the JsonNode produces by the readTree method, as it's recommended on the API documentation of JsonNode.toString().

String json = objectMapper.writeValueAsString(rootNode);


来源:https://stackoverflow.com/questions/51632180/when-using-jackson-system-out-printlnnew-objectmapper-readtreejsonstringobj

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