The Flexjson is a lightweight Java library for serializing and de-serializing java beans, maps, arrays, and collections in a JSON format. A JSONSerializer is the main class for performing 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
public JSONSerializer prettyPrint(boolean prettyPrint)
In the below program, Pretty print JSON using flexjson library
Example
import flexjson.*;
public class PrettyPrintJSONTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // pretty print
Employee emp = new Employee("Vamsi", "105", "Python Developer", "Python", "Pune");
String jsonStr = serializer.serialize(emp);
System.out.println(jsonStr);
}
}
// Employee class
class Employee {
private String name, id, designation, technology, location;
public Employee(String name, String id, String designation, String technology, String location) {
super();
this.name = name;
this.id = id;
this.designation = designation;
this.technology = technology;
this.location = location;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getDesignation() {
return designation;
}
public String getTechnology() {
return technology;
}
public String getLocation() {
return location;
}
}Output
{
"class": "Employee",
"designation": "Python Developer",
"id": "105",
"location": "Pune",
"name": "Vamsi",
"technology": "Python"
}