Java JSONTokener, JSONObject and JSONArray Complete Guide with Examples
In Java, JSONTokener, JSONObject, and JSONArray are commonly used to parse, read, create, and manipulate JSON data. These classes are available in the org.json library and are useful when working with REST APIs, JSON files, and test automation frameworks.
This tutorial explains JSONTokener, JSONObject, and JSONArray with practical Java examples and expected outputs.
1. What is JSONTokener in Java?
JSONTokener is a class from the org.json library that reads JSON input and processes it into tokens that can be used to construct JSON objects or arrays.
It can read JSON data from a String, Reader, or other supported input sources.
JSONTokener Example
import org.json.JSONTokener; import org.json.JSONObject; public class Main { public static void main(String[] args) { String jsonData = """ { "id": 101, "name": "Sumit", "salary": 75000, "department": "QA" } """; // Create JSONTokener JSONTokener tokener = new JSONTokener(jsonData); // Parse JSON into JSONObject JSONObject jsonObject = new JSONObject(tokener); // Read JSON values System.out.println("ID: " + jsonObject.getInt("id")); System.out.println("Name: " + jsonObject.getString("name")); System.out.println("Salary: " + jsonObject.getInt("salary")); System.out.println("Department: " + jsonObject.getString("department")); } }
Output
ID: 101
Name: Sumit
Salary: 75000
Department: QA
2. What is JSONObject in Java?
JSONObject represents JSON data as key-value pairs. It allows developers to create, read, update, and remove JSON properties.
JSONObject Example
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject employee = new JSONObject();
employee.put("id", 101);
employee.put("name", "Sumit");
employee.put("salary", 75000);
employee.put("department", "QA");
System.out.println("Name: " + employee.getString("name"));
System.out.println("Salary: " + employee.getInt("salary"));
employee.put("salary", 85000);
employee.remove("department");
System.out.println(employee.toString(4));
}
}
Output
Name: Sumit
Salary: 75000
{
"name": "Sumit",
"salary": 85000,
"id": 101
}
Note: The order of properties in a JSONObject is not guaranteed.
3. JSONObject with Nested JSON Example
A nested JSON object contains another JSON object as its property value. You can create nested objects using JSONObject and retrieve them using getJSONObject().
Java Example
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject address = new JSONObject();
address.put("city", "Bhubaneswar");
address.put("state", "Odisha");
address.put("country", "India");
JSONObject employee = new JSONObject();
employee.put("id", 101);
employee.put("name", "Sumit");
employee.put("address", address);
JSONObject empAddress = employee.getJSONObject("address");
System.out.println("Name: " + employee.getString("name"));
System.out.println("City: " + empAddress.getString("city"));
System.out.println("State: " + empAddress.getString("state"));
System.out.println(employee.toString(4));
}
}
Output
Name: Sumit
City: Bhubaneswar
State: Odisha
4. JSONTokener with JSONObject and JSONArray Example
This example demonstrates how to read raw JSON input using JSONTokener, convert it into a JSONObject, extract individual values, retrieve an array, and print formatted JSON output.
Java Example
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JsonParserDemo {
public static void main(String[] args) {
// Raw JSON string input
String rawJson = "{"name": "Aarav", "age": 28, "skills": ["Java", "SQL"]}";
// Initialize JSONTokener
JSONTokener tokener = new JSONTokener(rawJson);
// Convert JSON input into JSONObject
JSONObject userObject = new JSONObject(tokener);
// Extract individual values
String name = userObject.getString("name");
int age = userObject.getInt("age");
JSONArray skills = userObject.getJSONArray("skills");
// Print extracted data
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("First Skill: " + skills.getString(0));
// Pretty-print JSON
System.out.println("nPretty-Printed JSONObject:n"
+ userObject.toString(4));
}
}
Output
Name: Aarav
Age: 28
First Skill: Java
Pretty-Printed JSONObject:
{
"skills": [
"Java",
"SQL"
],
"name": "Aarav",
"age": 28
}
Execution Flow
- Store JSON data in a String variable.
- Create a JSONTokener instance using the JSON String.
- Pass JSONTokener to the JSONObject constructor.
- Retrieve individual properties using their keys.
- Retrieve the skills array using getJSONArray().
- Access the first array element using getString(0).
- Print formatted JSON using toString(4).
5. What is JSONArray in Java?
JSONArray represents an ordered collection of JSON values. It is commonly used when JSON data contains arrays of strings, numbers, objects, or other arrays.
JSONArray Example
import org.json.JSONArray;
public class Main {
public static void main(String[] args) {
JSONArray skills = new JSONArray();
skills.put("Java");
skills.put("Selenium");
skills.put("Playwright");
skills.put("SQL");
System.out.println("First Skill: " + skills.getString(0));
System.out.println("Second Skill: " + skills.getString(1));
System.out.println("Total Skills: " + skills.length());
for (int i = 0; i < skills.length(); i++) {
System.out.println(skills.getString(i));
}
System.out.println(skills.toString(4));
}
}
Output
First Skill: Java
Second Skill: Selenium
Total Skills: 4
Java
Selenium
Playwright
SQL
[
"Java",
"Selenium",
"Playwright",
"SQL"
]
6. JSONObject with JSONArray Example
You can combine JSONObject and JSONArray to create complex JSON structures containing employee details and multiple skills.
Java Example
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONArray skills = new JSONArray();
skills.put("Java");
skills.put("Selenium");
skills.put("SQL");
JSONObject employee = new JSONObject();
employee.put("id", 101);
employee.put("name", "Sumit");
employee.put("age", 32);
employee.put("skills", skills);
System.out.println("ID: " + employee.getInt("id"));
System.out.println("Name: " + employee.getString("name"));
JSONArray empSkills = employee.getJSONArray("skills");
System.out.println("Employee Skills:");
for (int i = 0; i < empSkills.length(); i++) {
System.out.println(empSkills.getString(i));
}
System.out.println(employee.toString(4));
}
}
Output
ID: 101
Name: Sumit
Employee Skills:
Java
Selenium
SQL
7. Parse JSON Directly Using JSONObject
You do not always need to create a JSONTokener explicitly. The JSONObject constructor can directly parse a JSON String.
Java Example
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonData = "{"id":101,"name":"Sumit"}";
JSONObject obj = new JSONObject(jsonData);
System.out.println(obj.getInt("id"));
System.out.println(obj.getString("name"));
}
}
Output
101
Sumit
8. JSONTokener vs JSONObject vs JSONArray
| Feature | JSONTokener | JSONObject | JSONArray |
|---|---|---|---|
| Purpose | Reads and tokenizes JSON input | Represents JSON key-value pairs | Represents an ordered collection of values |
| Data structure | Input tokenizer | JSON object | JSON array |
| Access data | Reads tokens | Using keys | Using indexes |
| Add values | No | put() | put() |
| Read values | Reads tokens | getString(), getInt() | getString(), getInt() |
| Remove values | No | remove(key) | remove(index) |
| Common use | Parsing JSON input | Working with JSON objects | Working with JSON arrays |
9. Important JSONObject Methods
| Method | Description |
|---|---|
| put(key, value) | Adds or updates a property. |
| getString(key) | Gets a String value. |
| getInt(key) | Gets an Integer value. |
| getDouble(key) | Gets a Double value. |
| getBoolean(key) | Gets a Boolean value. |
| getJSONObject(key) | Gets a nested JSON object. |
| getJSONArray(key) | Gets a JSON array. |
| optString(key) | Gets a String value without throwing an exception for a missing key. |
| has(key) | Checks whether a property exists. |
| isNull(key) | Checks whether a property is null or missing. |
| remove(key) | Removes a property. |
| keys() | Returns an iterator over object keys. |
| length() | Returns the number of properties. |
| toString(4) | Prints formatted JSON with four-space indentation. |
10. Important JSONArray Methods
| Method | Description |
|---|---|
| put(value) | Adds a value to the array. |
| getString(index) | Gets a String at the specified index. |
| getInt(index) | Gets an Integer at the specified index. |
| getJSONObject(index) | Gets a JSON object at the specified index. |
| getJSONArray(index) | Gets a nested JSON array. |
| optString(index) | Safely gets a String value. |
| length() | Returns the number of elements. |
| remove(index) | Removes an element. |
| toString(4) | Prints formatted JSON. |
11. Maven Dependency for org.json
To use JSONTokener, JSONObject, and JSONArray, add the org.json dependency to your Maven project's pom.xml file.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250517</version>
</dependency>
Maven automatically downloads the required library and makes its classes available to your Java application.
12. Frequently Asked Questions
1. What is the difference between JSONTokener and JSONObject?
JSONTokener reads and tokenizes JSON input, whereas JSONObject represents JSON data as key-value pairs and provides methods to access and manipulate properties.
2. Can we parse JSON without JSONTokener?
Yes. You can directly pass a JSON String to the JSONObject constructor using new JSONObject(jsonString).
3. What is the difference between JSONObject and JSONArray?
JSONObject stores data as key-value pairs, whereas JSONArray stores an ordered collection of values that can be accessed using indexes.
4. How do we access nested JSON objects?
Use the getJSONObject(key) method to access a nested JSON object.
5. How do we access JSON array values?
Use getJSONArray(key) to retrieve an array and methods such as getString(index) or getInt(index) to access its elements.
6. How do we print formatted JSON in Java?
Use toString(4) to print JSON with four spaces of indentation.
7. Is org.json included in the Java JDK?
No. The org.json library is an external dependency. You need to add it through Maven, Gradle, or a JAR file.
8. What happens if a JSONObject key does not exist?
Methods such as getString() and getInt() throw a JSONException if the required key is missing. Use optional methods such as optString() when appropriate.
Conclusion
JSONTokener, JSONObject, and JSONArray are useful classes for handling JSON data in Java applications. JSONTokener helps read JSON input, JSONObject handles key-value pairs, and JSONArray manages ordered collections of JSON values.
These classes are particularly useful for REST API testing, test automation, JSON parsing, and working with external services that return JSON responses.

No comments:
Post a Comment