We can pretty-print a JSON using the toString(int indentFactor) method of org.json.JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.
public java.lang.String toString(int indentFactor)
Let us create a JSON Object.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@Test
public void passBodyAsJsonArray1() {
// Creating JSON array to add first JSON object
JSONArray array1 = new JSONArray();
array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
720000));
// Creating JSON array
JSONArray array2 = new JSONArray();
array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
365000));
// Create JSON Object to add JSONArrays
JSONObject data1 = new JSONObject();
data1.put("employee1", array1);
data1.put("employee2", array2);
System.out.println(data1);
}
}
The output of the above program is

Add toString(int indentFactor) method to the above program.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@Test
public void passBodyAsJsonArray1() {
// Creating JSON array to add first JSON object
JSONArray array1 = new JSONArray();
array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
720000));
// Creating JSON array
JSONArray array2 = new JSONArray();
array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
365000));
// Create JSON Object to add JSONArrays
JSONObject data1 = new JSONObject();
data1.put("employee1", array1);
data1.put("employee2", array2);
System.out.println(data1.toString(4));
}
}
The output of the above program is

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!