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;

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" ]
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap