The following code snippet show you how to create JSON string using JSON-Java library. Create an instance of JSONObject and use the put() method to create a key-value pair for the JSON string. The JSONArray object can be used to create an array of list of values to the JSON string, we also use the put() method to add value to the list.
The JSONObject.toString() method accept parameter called indentFactor, this set the indentation level of the generated string, which also make the JSON string generated easier to read and look prettier.
package org.kodejava.json;
import org.json.JSONArray;
import org.json.JSONObject;
public class WriteJSONString {
public static void main(String[] args) {
JSONObject object = new JSONObject();
object.put("id", 1L);
object.put("name", "Alice");
object.put("age", 20);
JSONArray courses = new JSONArray();
courses.put("Engineering");
courses.put("Finance");
courses.put("Chemistry");
object.put("courses", courses);
String jsonString = object.toString(2);
System.out.println(jsonString);
}
}
The result of the code snippet above is:
{
"courses": [
"Engineering",
"Finance",
"Chemistry"
],
"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 scale and paint an image in Swing? - December 1, 2026
- How do I arrange components using BorderLayout in Java Swing? - December 1, 2026
- How do I map a Java class to a database table? - November 30, 2026
Thank you. I was struggling with one-line JSON files. The
indentFactorintoString(n)function saved me!