Back to Java
2026-02-118 min read

JSON Intro (Java)

Learn JSON Intro (Java) step by step with clear examples and exercises.

Why This Matters

In today's world, efficient data handling is crucial for various applications, including real-world development projects, interview preparation, and debugging common issues that arise during data manipulation. This lesson aims to provide you with a comprehensive understanding of working with JSON (JavaScript Object Notation) in Java, a powerful tool for exchanging data between servers and clients.

Prerequisites

To fully understand this lesson, you should have a solid foundation in the following topics:

  1. Basic Java syntax (variables, loops, methods)
  2. Object-Oriented Programming concepts in Java
  3. Exception handling and error management
  4. I/O operations in Java (FileReader, FileWriter, BufferedReader, etc.)
  5. Understanding of data structures such as arrays and objects
  6. Familiarity with classes and their properties and methods in Java
  7. Basic understanding of RESTful web services
  8. Understanding the structure and syntax of JSON data

Core Concept

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It's based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 16, 1999. JSON is commonly used for asynchronous browser/server communication, between servers, and in various data binding clients that can access a RESTful web service.

JSON Syntax

JSON consists of four types of data structures:

  • Objects (key-value pairs enclosed in curly braces {})
  • Arrays (ordered collections of values enclosed in square brackets [])
  • Scalars (strings, numbers, boolean, and null)
  • Comments (enclosed in /* */)

JSON in Java

Java has built-in support for JSON through the org.json package. To use it, you'll need to include the json.jar file in your project's classpath. This lesson will focus on using this built-in package for handling JSON data in Java.

JSONObject

The JSONObject class is used to represent a JSON object (an unordered collection of key-value pairs). It provides methods for adding, accessing, and removing key-value pairs, as well as converting the JSONObject to a string or reading a JSON string into a JSONObject.

JSONArray

The JSONArray class is used to represent a JSON array (an ordered collection of values). It provides methods for adding, accessing, and removing elements from the array, as well as converting the JSONArray to a string or reading a JSON string into a JSONArray.

JSON Object Manipulation

Creating a JSONObject

To create a new JSONObject in Java, use the following code:

JSONObject jsonObj = new JSONObject();

Adding Key-Value Pairs to a JSONObject

You can add key-value pairs to a JSONObject using the put() method. For example:

jsonObj.put("name", "John");
jsonObj.put("age", 30);
jsonObj.put("city", "New York");

Accessing Key-Value Pairs from a JSONObject

To access the value of a key in a JSONObject, use the get() method:

String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");

Removing Key-Value Pairs from a JSONObject

To remove a key-value pair from a JSONObject, use the remove() method:

jsonObj.remove("name");

JSON Array Manipulation

Creating a JSONArray

To create a new JSONArray in Java, use the following code:

JSONArray jsonArray = new JSONArray();

Adding Elements to a JSONArray

You can add elements to a JSONArray using the put() method or the append() method. For example:

jsonArray.put(new JSONObject().put("fruit1", "apple").put("fruit2", "banana"));
jsonArray.append("orange");

Accessing Elements from a JSONArray

To access an element in a JSONArray by its index, use the get() method:

JSONObject fruitObj = jsonArray.getJSONObject(0);
String fruit1 = fruitObj.getString("fruit1");

Removing Elements from a JSONArray

To remove an element from a JSONArray by its index, use the remove() method:

jsonArray.remove(0);

Reading and Writing JSON Data

Reading JSON Data from a File

To read JSON data from a file in Java, use the following steps:

  1. Create a BufferedReader to read the file.
  2. Read each line of the file into a String.
  3. Convert the String to a JSONObject using the JSONObject(String jsonStr) constructor.
  4. Access the data from the JSONObject as needed.

Here's an example:

BufferedReader reader = new BufferedReader(new FileReader("data.json"));
String line;
StringBuilder jsonStr = new StringBuilder();
while ((line = reader.readLine()) != null) {
jsonStr.append(line);
}
JSONObject obj = new JSONObject(jsonStr.toString());
// Access data from the JSONObject as needed...

Writing JSON Data to a File

To write JSON data to a file in Java, use the following steps:

  1. Create a FileWriter to write the file.
  2. Convert your JSONObject or JSONArray to a String using the toString() method.
  3. Write the String to the FileWriter.
  4. Close the FileWriter.

Here's an example:

JSONObject jsonObj = new JSONObject();
// Add data to the JSONObject...
FileWriter file = new FileWriter("data.json");
file.write(jsonObj.toString());
file.close();

Worked Example

Let us create a simple example of reading and writing JSON data using Java's built-in org.json package.

import org.json.*;
import java.io.*;

public class Main {
public static void main(String[] args) throws Exception {
// Creating JSON Object
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "John");
jsonObj.put("age", 30);
jsonObj.put("city", "New York");

// Adding a JSON Array
JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject().put("fruit1", "apple").put("fruit2", "banana"));
jsonObj.accumulate("fruits", jsonArray);

// Writing to a file
FileWriter file = new FileWriter("data.json");
jsonObj.write(file);
file.close();

// Reading from a file
JSONObject obj = new JSONObject(new FileReader("data.json"));
System.out.println(obj.getString("name"));
System.out.println(obj.getJSONArray("fruits").getJSONObject(0).getString("fruit1"));
}
}

In the above example, we create a JSON object with three key-value pairs and an array of two key-value pairs representing fruits. We then write it to a file named "data.json". Later, we read the data from the file and print the value of the "name" key and the first fruit in the array.

Common Mistakes

  1. Forgetting to include the json.jar file in the classpath.
  2. Not properly importing the org.json package.
  3. Misusing JSONObject methods (put vs. accumulate, etc.)
  4. Incorrectly parsing JSON data using JSONObject.
  5. Ignoring exceptions when reading or writing JSON files.
  6. Attempting to add duplicate keys to a JSONObject without overwriting the previous value.
  7. Not handling null values appropriately when working with JSON data.
  8. Incorrectly converting JSON data between JSONObject and JSONArray.
  9. Using the get() method on a JSONObject that contains an array for a key, instead of using the getJSONArray() or getJSONObject() methods.
  10. Not properly handling exceptions when reading or writing JSON files, such as FileNotFoundException or IOException.

Subheadings under Common Mistakes:

  • Handling Null Values
  • Converting Between JSONObject and JSONArray
  • Properly Accessing Data from JSONObjects and JSONArrays

Practice Questions

  1. Write a Java program to convert the following JSON object to a String:
{
"employees": [
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]
}
  1. Write a Java program to read JSON data from a file and store it in a List of custom Employee objects.
  2. Write a Java program to serialize an ArrayList of custom Student objects into a JSON array, then write the JSON array to a file.
  3. Write a Java program to deserialize a JSON string representing an ArrayList of custom Student objects.
  4. Write a Java program to handle null values in a JSON object and convert it to a String.
  5. Write a Java program to convert a JSONObject to a JSONArray and vice versa.
  6. Write a Java program that reads a JSON file, processes the data, and writes the processed data back to another JSON file.
  7. Write a Java program that validates a given JSON string against a schema using a library like JsonSchema or FasterXML's SchemaValidator.
  8. Write a Java program that generates a random JSON object with a specified number of properties and values.
  9. Write a Java program that merges two JSON objects, combining their key-value pairs into one JSON object.

FAQ

Q: What happens if I try to write a JSON object with duplicate keys?

A: If you attempt to add duplicate keys to a JSONObject, the last value assigned to that key will overwrite the previous one. To avoid this issue, consider using an ArrayList of JSONObjects or handling the duplicate keys appropriately before writing to the file.

Q: Can I use JSON in Java without the org.json package?

A: Yes, there are alternative libraries like Gson and Jackson for handling JSON data in Java, but we'll focus on the built-in org.json package in this lesson.

Q: How can I handle null values when working with JSON data in Java?

A: To handle null values, you can use the opt() method instead of the get() method when accessing keys from a JSONObject. The opt() method returns an Optional object that allows you to check if the value is present before using it.

Q: How do I convert a JSONObject to a JSONArray and vice versa in Java?

A: To convert a JSONObject to a JSONArray, use the keys() method to get all the keys from the JSONObject, then iterate through the keys and create a new JSONArray with the corresponding values. To convert a JSONArray to a JSONObject, you can use the JSONObject's accumulate() method to add each element in the array as a key-value pair.

Q: What is the difference between put() and accumulate() when working with JSON data in Java?

A: The put() method adds or updates a key-value pair in a JSONObject, replacing any existing value for that key. The accumulate() method allows you to add multiple key-value pairs to a JSONObject without overwriting existing values. If the key already exists, it will be added as an additional element in an array associated with that key.

Q: How do I properly access data from JSONObjects and JSONArrays in Java?

A: To access data from a JSONObject, use the appropriate method for the type of value you expect (getString(), getInt(), getBoolean(), etc.). To access data from a JSONArray, use the get() method with an index or iterate through the array using a loop.

Q: What are some best practices when working with JSON data in Java?

A: Some best practices include properly handling exceptions, validating JSON data against a schema, avoiding duplicate keys, and using appropriate methods for accessing and manipulating JSON data. Additionally, consider using libraries like Gson or Jackson for more advanced features and better performance.

JSON Intro (Java) | Java | XQA Learn