In JSON-Java we can make a pretty-printed JSON string by specifying an indentFactor
to the JSONObject
‘s toString()
method. The indent factor is the number of spaces to add to each level of indentation.
If indentFactor
> 0 and the JSONObject
has only one key, the JSON string will be printed a single line, and if the JSONObject
has 2 or more keys, the JSON string will be printed in multiple lines.
Let’s create a pretty-printed JSONObject
text using the code below.
package org.kodejava.json;
import org.json.JSONArray;
import org.json.JSONObject;
public class PrettyPrintJSON {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1L);
jsonObject.put("name", "Alice");
jsonObject.put("age", 20);
JSONArray courses = new JSONArray(
new String[]{"Engineering", "Finance"});
jsonObject.put("courses", courses);
// Default print without indent factor
System.out.println(jsonObject);
// Pretty print with 2 indent factor
System.out.println(jsonObject.toString(2));
}
}
Running this code produces the following output:
{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
{
"courses": [
"Engineering",
"Finance"
],
"name": "Alice",
"id": 1,
"age": 20
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024