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


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

Advertisements

Advertisements
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.