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!

Top Hashtags:

Advertisements

Advertisements




Advertisements