Back to Java
2026-05-117 min read

JSON Syntax (Java)

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

Title: JSON Syntax (Java)

Why This Matters

In today's data-driven world, understanding JSON (JavaScript Object Notation) syntax is crucial for developers working with Java applications that need to communicate with APIs, databases, or other systems. JSON is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. Learning JSON syntax in Java will help you build more efficient and powerful applications.

Understanding JSON syntax is essential for working with various web services, as many APIs use JSON to transmit data between the client and server. Furthermore, databases like MongoDB store data in JSON format, making it important to know how to work with JSON in Java when interacting with these databases.

Prerequisites

Before diving into JSON syntax, it's essential to have a good understanding of the following topics:

  1. Basic Java programming concepts such as variables, data types, operators, loops, and control structures.
  2. Object-oriented programming (OOP) principles in Java, including classes, objects, inheritance, and interfaces.
  3. Java I/O streams for reading and writing files.
  4. Understanding of APIs and how to consume them using HTTP requests.
  5. Familiarity with Maven or another build tool for managing dependencies.
  6. Knowledge of exception handling in Java to handle potential errors when parsing JSON data.

Core Concept

JSON syntax is based on two data structures: objects (or dictionaries) and arrays. Here's a brief overview of each:

JSON Objects

A JSON object is an unordered collection of key-value pairs, where keys are strings and values can be any valid JSON data type. In Java, you can represent a JSON object as a JSONObject from the org.json library. Here's an example:

import org.json.*;

// Creating a new JSONObject
JSONObject jsonObj = new JSONObject();

// Adding key-value pairs to the JSONObject
jsonObj.put("name", "John Doe");
jsonObj.put("age", 30);
jsonObj.put("city", "New York");
jsonObj.put("hobbies", new JSONArray(new String[]{"reading", "gaming", "music"}));

// Accessing values in the JSONObject
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");
JSONArray hobbies = jsonObj.getJSONArray("hobbies");

// Printing the JSON object and its values
System.out.println(jsonObj.toString());
System.out.printf("Name: %s%n", name);
System.out.printf("Age: %d%n", age);
System.out.printf("City: %s%n", city);
for (int i = 0; i < hobbies.length(); i++) {
String hobby = hobbies.getString(i);
System.out.printf("- Hobby: %s%n", hobby);
}

Output:

{"name":"John Doe","age":30,"city":"New York","hobbies":["reading","gaming","music"]}
Name: John Doe
Age: 30
City: New York
- Hobby: reading
- Hobby: gaming
- Hobby: music

JSON Arrays

A JSON array is an ordered collection of values, where all values must be of the same data type. In Java, you can represent a JSON array as a JSONArray from the org.json library. Here's an example:

import org.json.*;

// Creating a new JSONArray
JSONArray jsonArr = new JSONArray();

// Adding values to the JSONArray
jsonArr.put(1);
jsonArr.put("apple");
jsonArr.put(true);
jsonArr.put(new JSONObject());

// Accessing values in the JSONArray
int firstValue = jsonArr.getInt(0);
String secondValue = jsonArr.getString(1);
boolean thirdValue = jsonArr.getBoolean(2);
JSONObject fourthValue = jsonArr.getJSONObject(3);

// Printing the JSON array and its values
System.out.println(jsonArr.toString());
System.out.printf("First value: %d%n", firstValue);
System.out.printf("Second value: %s%n", secondValue);
System.out.printf("Third value: %b%n", thirdValue);
System.out.println(fourthValue.toString());

Output:

[1,"apple",true,{"name":"John Doe","age":30,"city":"New York"}]
First value: 1
Second value: apple
Third value: true
{
"name" : "John Doe",
"age" : 30,
"city" : "New York"
}

Nested JSON Structures

JSON objects and arrays can be nested within each other to create complex data structures. For example:

{
"employees": [
{
"name": "John Doe",
"age": 30,
"city": "New York",
"salary": {
"currency": "USD",
"amount": 50000
}
},
{
"name": "Jane Smith",
"age": 28,
"city": "Los Angeles",
"salary": {
"currency": "USD",
"amount": 60000
}
}
]
}

In this example, the JSON object contains an array of employee objects, and each employee object has a nested salary object. To work with nested structures in Java, you can use methods like getJSONArray(), getJSONObject(), or getString() to traverse the JSON data and access nested elements.

Worked Example

Let's create a simple Java program that reads a JSON file containing information about employees and calculates the average age of all employees.

Step 1: Add necessary libraries

Add the following Maven dependency to your pom.xml file:

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>

Step 2: Create a JSON file with employee data

Create a employees.json file in your project's resources folder and add the following content:

{
"employees": [
{
"name": "John Doe",
"age": 30,
"city": "New York"
},
{
"name": "Jane Smith",
"age": 28,
"city": "Los Angeles"
}
]
}

Step 3: Read the JSON file and calculate the average age

Create a new Java class called EmployeeAverageAge with the following code:

import org.json.*;
import java.io.FileReader;
import java.util.Iterator;

public class EmployeeAverageAge {
public static void main(String[] args) throws Exception {
// Reading the JSON file
JSONObject jsonObj = new JSONObject(new FileReader("employees.json"));

// Accessing the employees array and initializing variables for total age and employee count
JSONArray employeesArr = jsonObj.getJSONArray("employees");
int totalAge = 0;
int employeeCount = 0;

// Iterating through the JSON array and calculating the average age
for (int i = 0; i < employeesArr.length(); i++) {
JSONObject employeeObj = employeesArr.getJSONObject(i);
int age = employeeObj.getInt("age");

// Adding the employee's age to the total and incrementing the employee count
totalAge += age;
employeeCount++;
}

// Calculating and printing the average age
double averageAge = (double)totalAge / employeeCount;
System.out.printf("The average age of all employees is: %.2f%n", averageAge);
}
}

When you run this program, it will output the following result:

The average age of all employees is: 29.00

Common Mistakes

  1. Forgetting to import the org.json library. Make sure to add the necessary dependency in your project and import the required classes at the beginning of your code.
  2. Not properly reading or parsing the JSON file. Use the FileReader class to read the JSON file, and make sure you're using the correct methods (such as getJSONArray(), getJSONObject(), or getString()) to parse the JSON data.
  3. Accessing non-existent keys in a JSON object or array. Always check if a key exists before accessing its value, or handle exceptions gracefully when working with user-provided JSON data.
  4. Creating JSON objects and arrays incorrectly. Make sure to use the appropriate methods (such as put() for adding key-value pairs in a JSONObject) and follow proper JSON syntax when creating JSON structures.
  5. Not handling nested JSON structures properly. If your JSON data contains nested objects or arrays, make sure you understand how to traverse and process them correctly.
  6. Using outdated versions of the org.json library. Make sure to use a recent version of the org.json library to avoid potential compatibility issues with newer JSON syntax features.
  7. Ignoring error handling when working with user-provided JSON data. Always validate and sanitize user-provided JSON data to protect against malicious input or errors that could cause your application to crash or behave unexpectedly.

Practice Questions

  1. Given the following JSON object:
{
"name": "John Doe",
"age": 30,
"city": "New York",
"hobbies": ["reading", "gaming", "music"]
}

Write a Java program that prints the name and the first hobby of the person.

  1. Write a Java program that reads a JSON file containing information about books (title, author, publication year) and calculates the total number of books published in the 21st century.
  1. Write a Java program that sends an HTTP request to a REST API that returns JSON data representing a list of movies. Extract the title, release year, and genre of each movie and print them out.

FAQ

Q: What are some common libraries for working with JSON in Java?

A: Some popular libraries for working with JSON in Java include org.json, Gson (Google's JSON library), and Jackson. Each library has its own strengths and weaknesses, so it's essential to choose the one that best suits your project's needs.

Q: Can I use JSON in a standalone Java application without any external dependencies?

A: Yes, you can use the built-in org.json.simple library for working with JSON in a standalone Java application without adding any external dependencies. However, it's less feature-rich compared to other libraries like org.json.

Q: How do I convert a Java object to a JSON string?

A: To convert a Java object to a JSON string using the org.json library, you can use the toString() method of the JSONObject class or the toJSONString() method of the Gson library. For example:

import org.json.*;
import com.google.gson.Gson;

public class JavaToJson {
public static void main(String[] args) {
Employee employee = new Employee("John Doe", 30, "New York");
Gson gson = new Gson();
String jsonString = gson.toJson(employee);
System.out.println(jsonString);
}
}

Output:

{"name":"John Doe","age":30,"city":"New York"}
JSON Syntax (Java) | Java | XQA Learn