JSON String tidy/formatter for Java

With gson you can do:

JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();

JsonElement el = parser.parse(jsonString);
jsonString = gson.toJson(el); // done

You don't need an outside library.

Use the built in pretty printer in Sling's JSONObject: http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

public java.lang.String toString(int indentFactor) throws JSONException

Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the data structure is acyclical.

Parameters:

indentFactor - The number of spaces to add to each level of indentation.

Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).

Throws: JSONException - If the object contains an invalid number.


Many JSON libraries have a special .toString(int indentation) method

// if it's not already, convert to a JSON object
JSONObject jsonObject = new JSONObject(jsonString);
// To string method prints it with specified indentation
System.out.println(jsonObject.toString(4));