Pretty-Print JSON in Java Pretty-Print JSON in Java java java

Pretty-Print JSON in Java


Google's GSON can do this in a nice way:

Gson gson = new GsonBuilder().setPrettyPrinting().create();JsonParser jp = new JsonParser();JsonElement je = jp.parse(uglyJsonString);String prettyJsonString = gson.toJson(je);

or since it is now recommended to use the static parse method from JsonParser you can also use this instead:

Gson gson = new GsonBuilder().setPrettyPrinting().create();JsonElement je = JsonParser.parseString​(uglyJsonString);String prettyJsonString = gson.toJson(je);

Here is the import statement:

import com.google.gson.*;

Here is the Gradle dependency:

implementation 'com.google.code.gson:gson:2.8.7'


I used org.json built-in methods to pretty-print the data.

JSONObject json = new JSONObject(jsonString); // Convert text to objectSystem.out.println(json.toString(4)); // Print it with specified indentation

The order of fields in JSON is random per definition. A specific order is subject to parser implementation.


With Jackson (com.fasterxml.jackson.databind):

ObjectMapper mapper = new ObjectMapper();System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))

From: How to enable pretty print JSON output (Jackson)

I know this is already in the answers, but I want to write it separately here because chances are, you already have Jackson as a dependency and so all you will need would be an extra line of code