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>20230618</version>
<type>bundle</type>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thank you. I was struggling with one-line JSON files. The
indentFactor
intoString(n)
function saved me!