Pretty Print JSON Using Flexjson Library in Java



Pretty printing JSON is a process of formatting our JSON data to make it more readable and good-looking.

The prettyPrint() Method of Flexjson

We will be using the Flexjson library to pretty print JSON in Java. The Flexjson library is a lightweight library that is used for serializing as well as deserializing Java objects to and from JSON.

A JSONSerializer is the main class for performing the serialization of Java objects to JSON and by default, performs a shallow serialization. We can pretty-print JSON using the prettyPrint(boolean prettyPrint) method of JSONSerializer class.

Syntax of prettyPrint()

The syntax of the prettyPrint() method is as follows:

public JSONSerializer prettyPrint(boolean prettyPrint)

To use the Flexjson library, we need to add it to our project. If you are using Maven, add this to your pom.xml file:

<dependency>
<groupId>org.flexjson</groupId>
<artifactId>flexjson</artifactId>
<version>3.3</version>
</dependency>

If you do not use Maven, you can download the jar file from here.

Steps to Pretty Print JSON using Flexjson

Following are the steps to pretty print JSON using the Flexjson library:

  • Create a class Person with fields for name and age.
  • Use JSONSerializer to pretty print a Person object.
  • Print the pretty printed JSON string. Modify the Person object.
  • Convert the modified Person object to a JSON string using the toJson(). Print the modified JSON string.
  • Deserialize the JSON string back to a Person object using the fromJson(). Print the deserialized Person object.
  • Use the prettyPrint() method to pretty print the JSON string. Print the pretty printed JSON string.

Example

Following is the code to pretty print JSON using the Flexjson library:

import org.flexjson.*;

public class PrettyPrintJsonExample {
   public static void main(String[] args) {
      // Create a Person object
      Person person = new Person("Ansh", 23);
      // Create a JSONSerializer object
      JSONSerializer serializer = new JSONSerializer();
      // Pretty print the JSON string
      String jsonString = serializer.prettyPrint(true).serialize(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;
   }
}

The output of the above code will be:

Pretty Printed JSON: {
   "name" : "Ansh",
   "age" : 23
}
Updated on: 2025-05-12T14:22:00+05:30

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements