The Pretty print JSON in Java tutorial shows you how to use Jackson pretty print for JSON Object and String in the console.
Other interesting posts you may like
Pretty Print JSON Object
Example to convert Object and jackson pretty print its output in JSON format.
1 2 3 4 5 6 7 8 9 |
Student student = new Student(); //set student data student.setName("David"); student.setAge("35"); student.setCourses(new String[]{"Math","Foreign Language","Animal Biology"}); //print json format ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(student)); |
And the json output is in compact mode.
1 |
{"name":"David","age":35,"courses":["Math","Foreign Language","Animal Biology"]} |
To enable jackson pretty print, use writerWithDefaultPrettyPrinter.
1 2 |
ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student)); |
And here is pretty output
1 2 3 4 5 6 7 8 9 |
{ "name": "David", "age": 35, "courses": [ "Math", "Foreign Language", "Animal Biology" ] } |
Pretty Print JSON String
Now we can try to use writerWithDefaultPrettyPrinter again .
1 2 |
String jsonString = "{"name":"David","age":35,"courses":["Math","Foreign Language","Animal Biology"]}"; System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonString)); |
Here is output:
1 |
"{"name":"David","age":35,"courses":["Math","Foreign Language","Animal Biology"]}" |
And not what we want, json string is still in compact mode. We solve it by using a bit tricky that bind the JSON string to Object class before pretty print it.
1 2 3 |
String jsonString = "{"name":"David","age":35,"courses":["Math","Foreign Language","Animal Biology"]}"; Object jsonObject = mapper.readValue(jsonString, Object.class); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject)); |
And here is pretty output
1 2 3 4 5 6 7 8 9 |
{ "name": "David", "age": 35, "courses": [ "Math", "ForeignLanguage", "AnimalBiology" ] } |
That’s it. This Pretty print JSON in Java tutorial is quite simple by using Jackson framework. You can get JSON pretty print with good tool online Pretty Print JSON