Pretty Print JSON String in Java Console Output

Post Banner

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;


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);


        } catch (IOException e) {
        } catch (Exception e) {
  "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" ]

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.