在Jackson中,我们可以使用writerWithDefaultPrettyPrinter()
漂亮地打印JSON输出。
用Jackson 2.9.8测试
1.1默认情况下,Jackson以紧凑格式打印:
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
输出量
{"name":"mkyong","age":38,"skills":["java","python","node","kotlin"]}
1.2启用按需漂亮打印。
ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); // pretty print String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(json);
输出量
{ "name" : "mkyong", "age" : 38, "skills" : [ "java", "python", "node", "kotlin" ] }
1.3全局启用漂亮打印。
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; // pretty print ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json);
输出量
{ "name" : "mkyong", "age" : 38, "skills" : [ "java", "python", "node", "kotlin" ] }
注意
要在HTML页面上显示漂亮的JSON输出,请使用pre
标签将其包装。<pre>${pretty-print-json-output}</pre>
注意– 2013/12/12
本文已更新为使用writerWithDefaultPrettyPrinter()
,不建议使用旧的defaultPrettyPrintingWriter()
。
最新评论: