-
Notifications
You must be signed in to change notification settings - Fork 8
Formatting
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"
}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.
The JSONFormatter class also has some settings that can be changed with setter methods.
-
JSONFormatter#setUseCRLFdetermines if\r\n(true) or\n(false;default) is used as line break -
JSONFormatter#setUseTabsdetermines if tabulators (true;default) or whitespaces (false) are used as indent characters -
JSONFormatter#setIndentdetermines the amount of indent characters are used per indent level (default is1)
Since version 2.1.0 these settings can also be set with the constructor.
JSONFormatter formatter = new JSONFormatter();
formatter.setUseCRLF(true);
formatter.setUseTabs(false);
formatter.setIndent(2);
String formatted = formatter.format(myJSONObject);
System.out.println(formatted);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.
JSONFormatter formatter = new JSONFormatter();
String minimized = formatter.minimize(myFormattedJSONData);
System.out.println(minimized);