Skip to content

Formatting

Ralph Niemitz edited this page Dec 6, 2022 · 3 revisions

Basic Pretty-Print

It is possible to format JSON data with the JSONFormatter#format method. Just use your JSON DOM as parameter and it should return something like this:

Original:

{"first_name":"John","last_name":"Doe"}

Formatted:

{
	"first_name":"John",
	"last_name":"Doe"
}

Code Example

JSONFormatter formatter = new JSONFormatter();
String formatted = formatter.format(myJSONObject);
System.out.println(formatted);

It is recommended to use the JSONFromatter#format(Writer) overloaded method in case you work with large JSON DOMs which may cause OutOfMemoryErrors.

Pretty-Print with Settings

The JSONFormatter class also has some settings that can be changed with setter methods.

  • JSONFormatter#setUseCRLF determines if \r\n (true) or \n (false;default) is used as line break
  • JSONFormatter#setUseTabs determines if tabulators (true;default) or whitespaces (false) are used as indent characters
  • JSONFormatter#setIndent determines the amount of indent characters are used per indent level (default is 1)

Since version 2.1.0 these settings can also be set with the constructor.

Code Example

JSONFormatter formatter = new JSONFormatter();
formatter.setUseCRLF(true);
formatter.setUseTabs(false);
formatter.setIndent(2);

String formatted = formatter.format(myJSONObject);
System.out.println(formatted);

Minimizing

Minimizing is the reverse of Pretty-Print. Instead of formatting the JSON data in a human readable way it is pressed together in a single line. This can be beneficial when you want to reduce the required memory size of a JSON string by removing tabulators, whitespaces and line breaks. It is also possible to stream the minimization process to avoid OutOfMemoryErrors.

Code Example

JSONFormatter formatter = new JSONFormatter();
String minimized = formatter.minimize(myFormattedJSONData);
System.out.println(minimized);

Clone this wiki locally