在这个快速教程中,我们将学习如何使用Jackson库来美化(pretty print)JSON对象并将其打印到控制台或外部文件。
添加依赖项
首先,在你的pom.xml
中添加以下依赖项:
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>LATEST_VERSION</version> <!-- 请替换为Maven中央仓库上的最新版本 -->
</dependency>
这个依赖会自动引入jackson-core
和jackson-annotations
。
启用美化输出
Jackson提供了两种简单的方法来启用JSON美化输出:
- 使用
ObjectMapper.writerWithDefaultPrettyPrinter()
方法。 - 使用
ObjectMapper.enable(SerializationFeature.INDENT_OUTPUT)
方法。
两种方式都能产生相同的格式化效果。
完整示例
接下来,我们创建一个名为User
的类,并演示如何使用上述两种方法之一来美化JSON输出。
package net.javaguides.jackson;public class User {public int id;private String firstName, lastName, fullName;public User(int id, String firstName, String lastName, String fullName) {this.id = id;this.firstName = firstName;this.lastName = lastName;this.fullName = fullName;}// Getters and setters...
}
然后,我们在主程序中使用这两种方法之一来生成美化后的JSON输出:
package net.javaguides.jackson;import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;public class Demo {public static void main(String[] args) throws Exception {ObjectMapper mapper = new ObjectMapper();User user = new User(1, "Ramesh", "Fadatare", "Ramesh Fadatare");// Choose one of the following methods to enable pretty print:String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);// OR// mapper.enable(SerializationFeature.INDENT_OUTPUT);// String prettyJson = mapper.writeValueAsString(user);System.out.println(prettyJson);}
}
运行此程序将会输出格式化的JSON字符串到控制台。你可以选择任一方法来实现JSON的美化输出。