问题
现在我有一个org.fasterxml.jackson.databind.ObjectMapper
的实例,并希望得到aString
与漂亮的JSON。我的谷歌搜索的所有结果都提出了Jackson 1.x这样做的方法,我似乎无法找到适当的,不推荐使用2.2的方法。即使我不相信代码对于这个问题是绝对必要的,这就是我现在所拥有的:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println("\n\n----------REQUEST-----------");
StringWriter sw = new StringWriter();
mapper.writeValue(sw, jsonObject);
// Want pretty version of sw.toString() here
#1 热门回答(213 赞)
你可以通过设置你的ObjectMapper
之类的SerializationFeature.INDENT_OUTPUT
来启用漂亮打印:
mapper.enable(SerializationFeature.INDENT_OUTPUT);
#2 热门回答(33 赞)
根据mkyong,神奇的咒语是defaultPrintingWriter
至pretty print JSON:
较新版本:
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));
旧版本:
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));
似乎我很快就跳了一下枪。你可以试试gson,其707709822:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
希望这可以帮助...
#3 热门回答(28 赞)
jackson API已更改:
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());