
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pretty Print JSON Using Jackson Library in Java
A Jackson API is a Java-based library, and it can be useful to convert Java objects to JSON and JSON to Java objects. A Jackson API is faster than other API, needs less memory, and is good for large objects. We can process a JSON in three different ways: Streaming API, Tree Model, and Data Binding.
We can pretty print JSON using the writerWithDefaultPrettyPrinter() of the ObjectMapper class, which is a factory method for constructing an ObjectWriter that will serialize objects using the default pretty printer for indentation.
In this article, we will learn how to pretty print JSON using the Jackson library. In order to use the Jackson library, we will need to add it to our project. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.0</version> </dependency>
If you do not use Maven, you can download the jar file from here.
Steps to Pretty Print JSON using Jackson
Following are the steps to pretty print JSON using the Jackson library:
- Import the Jackson library, as we have already discussed.
- Then create a class Person with fields for name and age.
- Next, we will create a constructor and getter methods for the fields.
- Now, create a Person object.
- Then create an ObjectMapper object.
- Use the writerWithDefaultPrettyPrinter() method to create an ObjectWriter object.
- Call the writeValueAsString() method of the ObjectWriter object to convert the Person object to a JSON string.
- Print the pretty printed JSON string.
Example
The following is the code to pretty print JSON using the Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; public class PrettyPrintJsonExample { public static void main(String[] args) throws Exception { // Create a Person object Person person = new Person("Ansh", 23); // Create an ObjectMapper object ObjectMapper objectMapper = new ObjectMapper(); // Pretty print the JSON string ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); String jsonString = writer.writeValueAsString(person); // Print the pretty printed JSON string System.out.println("Pretty Printed JSON: " + jsonString); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
Following is the output of the above program -
Pretty Printed JSON: { "name" : "Ansh", "age" : 23 }