Back to Java
2025-12-126 min read

JSON Values (Java)

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

Title: JSON Values (Java) - A full guide for Java Developers

Why This Matters

In today's data-driven world, understanding JSON (JavaScript Object Notation) is essential for any Java developer. JSON 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 widely used as a data format in APIs and web applications, making it crucial for seamless communication between servers and clients.

Prerequisites

Before diving into JSON values in Java, you should have a good understanding of the following topics:

  • Basic Java programming concepts (variables, loops, methods)
  • Java object-oriented programming (classes, objects, inheritance)
  • Java I/O operations (reading and writing files)
  • Java exception handling
  • Familiarity with JSON structure and syntax is also beneficial but not required.

Core Concept

JSON is a text format that represents structured data as key-value pairs or arrays. In Java, JSON can be parsed using libraries like org.json or Gson. Let's explore how to work with JSON values in Java using the org.json library.

JSON Object

A JSON object is a collection of key-value pairs enclosed within curly braces {}. In Java, we can represent a JSON object as a JSONObject from the org.json package. Here's an example:

import org.json.*;

JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
jsonObject.put("city", "New York");
jsonObject.put("hobbies", new JSONArray(new String[]{"reading", "gaming", "coding"}));

System.out.println(jsonObject.toString()); // Output: {"name":"John Doe","age":30,"city":"New York","hobbies":["reading","gaming","coding"]}

JSON Array

A JSON array is an ordered collection of values enclosed within square brackets []. In Java, we can represent a JSON array as a JSONArray from the org.json package. Here's an example:

import org.json.*;

JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject("{\"name\":\"John Doe\", \"age\":30}"));
jsonArray.put(new JSONObject("{\"name\":\"Jane Smith\", \"age\":28}"));

System.out.println(jsonArray.toString()); // Output: [{"name":"John Doe","age":30}, {"name":"Jane Smith","age":28}]

Parsing JSON

To parse a JSON string in Java, we can use the JSONObject and JSONArray classes. Here's an example:

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

public class JsonExample {
public static void main(String[] args) throws IOException {
String json = "{\"name\":\"John Doe\", \"age\":30, \"cars\":[\"Ford\", \"BMW\", \"Fiat\"]}";
JSONObject jsonObject = new JSONObject(json);
System.out.println("Name: " + jsonObject.getString("name")); // Output: Name: John Doe
System.out.println("Age: " + jsonObject.getInt("age")); // Output: Age: 30
JSONArray carsArray = jsonObject.getJSONArray("cars");
for (int i = 0; i < carsArray.length(); i++) {
System.out.println("Car: " + carsArray.getString(i)); // Output: Car: Ford, Car: BMW, Car: Fiat
}
}
}

Reading JSON from a File

To read JSON data from a file in Java, we can use the JSONObject and FileReader classes. Here's an example:

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

public class JsonExample {
public static void main(String[] args) throws IOException {
File jsonFile = new File("data.json");
JSONObject jsonObject = new JSONObject(new FileReader(jsonFile));
System.out.println(jsonObject.toString());
}
}

Worked Example

Let's create a simple Java application that reads JSON data from a file and processes it.

  1. Create a new Java project in your favorite IDE (e.g., IntelliJ IDEA or Eclipse).
  2. Add the org.json library to your project dependencies. If you're using Maven, add this to your pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
  1. Create a new Java class called JsonExample.
  2. Replace the generated code with the following:
import org.json.*;
import java.io.*;

public class JsonExample {
public static void main(String[] args) throws IOException {
File jsonFile = new File("data.json");
JSONObject jsonObject = new JSONObject(new FileReader(jsonFile));
System.out.println(jsonObject.toString());

JSONArray usersArray = jsonObject.getJSONArray("users");
for (int i = 0; i < usersArray.length(); i++) {
JSONObject userObj = usersArray.getJSONObject(i);
System.out.println("Name: " + userObj.getString("name"));
System.out.println("Age: " + userObj.getInt("age"));
}
}
}
  1. Create a new file called data.json in the same directory as your Java project with the following content:
{
"name": "John Doe",
"age": 30,
"users": [
{
"name": "Alice",
"age": 25
},
{
"name": "Bob",
"age": 28
}
]
}
  1. Run the JsonExample class, and you should see the following output:
{"name":"John Doe","age":30,"users":[{"name":"Alice","age":25},{"name":"Bob","age":28}]}
Name: John Doe
Age: 30
Name: Alice
Age: 25
Name: Bob
Age: 28

Common Mistakes

  1. Forgetting to import the org.json library.
  2. Not properly handling JSON exceptions (e.g., JSONException) when parsing or accessing JSON data.
  3. Misunderstanding the difference between a JSON object and a JSON array, leading to incorrect data representation.
  4. Failing to close files when reading JSON from a file.
  5. Using outdated versions of the org.json library, which may not support newer JSON features or have compatibility issues with other libraries.
  6. Not properly handling null values in JSON data. To check if a value is null, use the isNull() method on a JSONObject or JSONArray.
  7. Not properly escaping special characters (e.g., quotes and backslashes) when creating JSON strings. To avoid issues, always use double quotes for keys and values and escape any special characters using a backslash (\).

Practice Questions

  1. Create a Java program that reads a JSON array containing user objects and calculates the total age of all users.
  2. Given a JSON string representing a product object (with properties name, price, and quantity), write a Java method to calculate the total cost of the products in an array.
  3. Write a Java program that reads a JSON file containing employee objects (with properties id, name, position, and salary) and sorts them by salary in descending order.
  4. Write a Java program that validates a JSON string against a given schema using the org.json.schema library.
  5. Implement a method to convert a Java object (represented as a Map) into a JSON string using the org.json library.

FAQ

What is JSON, and why is it important for web development?

  • JSON is a lightweight data interchange format used extensively in web development to exchange data between the client and server. It's easy for humans to read and write, and easy for machines to parse and generate, making it an essential part of modern web applications.

How do I parse a JSON string in Java?

  • In Java, you can use the org.json library to parse JSON strings. First, add the library to your project dependencies, then create a JSONObject or JSONArray instance using the new JSONObject(String json) or new JSONArray(String json) constructor and call methods like getString(), getInt(), or getJSONArray() to access the data.

What are some common mistakes when working with JSON in Java?

  • Common mistakes include forgetting to import the org.json library, not handling JSON exceptions, misunderstanding the difference between a JSON object and a JSON array, failing to close files when reading JSON from a file, using outdated versions of the org.json library, not properly handling null values in JSON data, and not properly escaping special characters in JSON strings.

How can I sort an array of JSON objects in Java?

  • To sort an array of JSON objects in Java, first convert it to a list of JSONObjects (e.g., using the toList() method). Then you can use Java's built-in sorting methods like Collections.sort() or Arrays.sort(), providing a custom comparator that compares the JSONObject properties as needed.

Are there any other libraries for parsing JSON in Java aside from org.json?

  • Yes, there are several other libraries available for parsing JSON in Java, such as Gson, Jackson, and FastJson. Each has its own advantages and trade-offs, so the choice depends on your specific needs and project requirements.

How do I validate a JSON string against a schema in Java?

  • To validate a JSON string against a schema in Java, you can use the org.json.schema library. First, add it to your project dependencies, then create a JSONSchema instance from your schema file (or define it programmatically) and call the validate() method on your JSONObject or JSONArray. The method will return a JSONSchemaValidator that can be used to check the validity of the JSON data.
JSON Values (Java) | Java | XQA Learn