略微加速

略速 - 互联网笔记

Jackson-如何启用漂亮的打印JSON输出

2021-12-03 leiting (2067阅读)

标签 JAVA

在Jackson中,我们可以使用writerWithDefaultPrettyPrinter()漂亮地打印JSON输出。

用Jackson 2.9.8测试

1.漂亮的JSON打印

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() 。


https://blog.csdn.net/cyan20115/article/details/106551962
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3