Jackson
Enable Pretty Print JSON Output using Jackson example
As you might have noticed in the previous JSON tutorials, the output of the programs is not properly aligned, which makes it hard to read.
For this demonstration we are going to use the Student
class from this example.
Student.java:
package com.javacodegeeks.java.core; public class Student { private int id; private String firstName; private String lastName; private int age; public Student(){ } public Student(String fname, String lname, int age, int id){ this.firstName = fname; this.lastName = lname; this.age = age; this.id = id; } public void setFirstName(String fname) { this.firstName = fname; } public String getFirstName() { return this.firstName; } public void setLastName(String lname) { this.lastName = lname; } public String getLastName() { return this.lastName; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void setId(int id){ this.id = id; } public int getId(){ return this.id; } @Override public String toString() { return new StringBuffer(" First Name : ").append(this.firstName) .append(" Last Name : ").append(this.lastName).append(" Age : ").append(this.age).append(" ID : ").append(this.id).toString(); } }
JacksonPrettyPrintingExample.java:
package com.javacodegeeks.java.core; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JacksonPrettyPrintingExample { public static void main(String[] args) { Student student = new Student("Jack", "Jones",12, 100 ); ObjectMapper mapper = new ObjectMapper(); try { System.out.println("Default output:"+mapper.writeValueAsString(student)); System.out.println("Pretty printing:\n"+mapper.defaultPrettyPrintingWriter().writeValueAsString(student)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
output:
Default output:{"id":100,"firstName":"Jack","lastName":"Jones","age":12}
Pretty printing:
{
"id" : 100,
"firstName" : "Jack",
"lastName" : "Jones",
"age" : 12
}
This was an example on how to enable Pretty Print JSON Output using Jackson.