
In order to pretty-print a JSON String in Java console output, we can make use of the Jackson Library, let's see an example,
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class PrettyPrintJson {
public static void main(String[] args) {
try {
String jsonString = "{\n" +
" \"artistName\":\"Michael Jackson\",\n" +
" \"albumName\":\"Thriller\",\n" +
" \"releaseYear\":1982,\n" +
" \"songsList\":[\n" +
" \"Wanna Be Startin Somethin\",\n" +
" \"Baby Be Mine\",\n" +
" \"The Girl Is Mine\",\n" +
" \"Thriller\",\n" +
" \"Beat it\",\n" +
" \"Billie Jean\",\n" +
" \"Human Nature\",\n" +
" \"P.Y.T. (Pretty Young Thing)\",\n" +
" \"The Lady in My Life\"\n" +
" ]\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
String prettyPrintedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
System.out.println(prettyPrintedJson);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
{
"artistName" : "Michael Jackson",
"albumName" : "Thriller",
"releaseYear" : 1982,
"songsList" : [ "Wanna Be Startin Somethin", "Baby Be Mine", "The Girl Is Mine", "Thriller", "Beat it", "Billie Jean", "Human Nature", "P.Y.T. (Pretty Young Thing)", "The Lady in My Life" ]
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!