ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
json = mapper.writeValueAsString(json);
编辑:
之前:
{"artifacts":[{"general":{"name":"jersey-client-2.26.jar","path":"doartifac/spielwiese-group-cache/org/glassfish/jersey/core/jersey-client/2.26/jersey-client-2.26.jar","pkg_type":"Maven","sha256":"3e44b7db8691eb0b2a6751eda888150b9ba1092a5805f11e4727fd4904407a41","component_id":"org.glassfish.jersey.core:jersey-client:2.26"},"issues":[],"licenses":[{"name":"CDDL-1.0","full_name":"Common Development and Distribution License (CDDL)\n 1.0","more_info_url":["http://www.opensource.org/licenses/cddl1.php","https://spdx.org/licenses/CDDL-1.0","https://spdx.org/licenses/CDDL-1.0.html","http://www.opensource.org/licenses/cddl1"],"components":["gav://org.glassfish.jersey.core:jersey-client:2.26"]},{"name":"GPL-2.0","full_name":"The GNU General Public License Version 2","more_info_url":["http://www.opensource.org/licenses/GPL-2.0","http://www.opensource.org/licenses/gpl-2.0.php","https://spdx.org/licenses/GPL-2.0","https://spdx.org/licenses/GPL-2.0.html","http://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html"],"components":["gav://org.glassfish.jersey.core:jersey-client:2.26"]}]}]}
之后:
"{\"artifacts\":[{\"general\":{\"name\":\"jersey-client-2.26.jar\",\"path\":\"doartifac/spielwiese-group-cache/org/glassfish/jersey/core/jersey-client/2.26/jersey-client-2.26.jar\",\"pkg_type\":\"Maven\",\"sha256\":\"3e44b7db8691eb0b2a6751eda888150b9ba1092a5805f11e4727fd4904407a41\",\"component_id\":\"org.glassfish.jersey.core:jersey-client:2.26\"},\"issues\":[],\"licenses\":[{\"name\":\"CDDL-1.0\",\"full_name\":\"Common Development and Distribution License (CDDL)\\n 1.0\",\"more_info_url\":[\"http://www.opensource.org/licenses/cddl1.php\",\"https://spdx.org/licenses/CDDL-1.0\",\"https://spdx.org/licenses/CDDL-1.0.html\",\"http://www.opensource.org/licenses/cddl1\"],\"components\":[\"gav://org.glassfish.jersey.core:jersey-client:2.26\"]},{\"name\":\"GPL-2.0\",\"full_name\":\"The GNU General Public License Version 2\",\"more_info_url\":[\"http://www.opensource.org/licenses/GPL-2.0\",\"http://www.opensource.org/licenses/gpl-2.0.php\",\"https://spdx.org/licenses/GPL-2.0\",\"https://spdx.org/licenses/GPL-2.0.html\",\"http://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html\"],\"components\":[\"gav://org.glassfish.jersey.core:jersey-client:2.26\"]}]}]}"
试着检查一下:使用Jackson将JSON字符串转换为漂亮的打印JSON输出
您需要首先读取现有的JSON对象,然后序列化它。因为现在您只是在序列化String。
UPD:你需要这样做:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = "here your ugly json";
Object jsonObject = mapper.readValue(json, Object.class);
String prettyFormatted = mapper.writeValueAsString(jsonObject);