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 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
Thank you. I was struggling with one-line JSON files. The
indentFactor
intoString(n)
function saved me!