You can format JSON String in Java using Jackson API's pretty print feature. As you might have noticed in the my previous JSON tutorials that the output of the programs is not properly formatted, which makes them hard to read, especially in large log files where there are so many other text, both JSON and normal text is there. That's why its advised to print JSON String properly formatted because then it will stand out in log file or console. Whenever we print JSON String from Java Programs by using method writeValueAsString(), it usually comes in one line, as shown in following example :
This is not very readable as you cannot see how many attributes are there, what is their name and value, compare it to following formatted output which is printed using Jackson's pretty print feature:
Its way better than earlier output, its much more readable. You can easily identify which one is just simple name value pair, which one is JSON array and much more. Wondering, how to nicely print JSON String, just checkout the example shown in next section.
{"name":"Virat","sport":"cricket","age":25,"id":121,"lastScores":[77,72,23,57,54,36,74,17]}
This is not very readable as you cannot see how many attributes are there, what is their name and value, compare it to following formatted output which is printed using Jackson's pretty print feature:
{
"name" : "Virat",
"sport" : "cricket",
"age" : 25,
"id" : 121,
"lastScores" : [ 77, 72, 23, 57, 54, 36, 74, 17 ]
}
Its way better than earlier output, its much more readable. You can easily identify which one is just simple name value pair, which one is JSON array and much more. Wondering, how to nicely print JSON String, just checkout the example shown in next section.