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>
<!-- https://search.maven.org/remotecontent?filepath=org/json/json/20220320/json-20220320.jar -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220320</version>
<type>bundle</type>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
Thank you. I was struggling with one-line JSON files. The
indentFactor
intoString(n)
function saved me!