Working with JSON Data in Java

Last Updated : 23 Dec, 2025

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data format used for data exchange. It is easy to read, write, and parse, making it widely used in web services and APIs. JSON files use the .json extension. JSON stores data in key–value pairs and supports arrays and nested objects.

Example: Storing student information in JSON format.

{
"Student": [
{
"Stu_id": "1001",
"Stu_Name": "Ashish",
"Course": "Java"
},
{
"Stu_id": "1002",
"Stu_Name": "Rana",
"Course": "Advance Java"
}
]
}

Working with JSON in Java

To read and write JSON data in Java, we commonly use third-party libraries. In this article, we use json-simple, a lightweight and beginner-friendly library.

Why json-simple?

  • Easy API (JSONObject, JSONArray)
  • Minimal setup
  • Supports encoding and decoding JSON data

Dependency Setup

Add the following dependency to your pom.xml file:

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>

Key Classes in json-simple

Class

Purpose

JSONObject

Represents a JSON object (Map-based)

JSONArray

Represents a JSON array (List-based)

JSONValue

Parses JSON text

JSONParser

Parses JSON from files or streams

JSON Encoding in Java(Write JSON)

JSON encoding means converting Java data into JSON format.

Example: Create and Print JSON Object.

Java
import org.json.simple.JSONObject;

public class JavaJsonEncoding {
    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("Full Name", "Ritu Sharma");
        jsonObject.put("Roll No.", 1704310046);
        jsonObject.put("Tuition Fees", 65400);
        System.out.println(jsonObject);
    }
}

Output:

WriteJson
Snapshot of JavaJsonEncoding.java File

Explanation:

  • JSONObject internally works like a HashMap
  • put() stores key–value pairs
  • The object is automatically converted to JSON string format

JSON Decoding in Java (Read JSON)

JSON decoding means converting JSON data into Java objects.

Java
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JavaJsonDecoding {
    public static void main(String[] args) {
        String jsonString ="{\"Full Name\":\"Ritu Sharma\",\"Tuition Fees\":65400.0,\"Roll No.\":1704310046}";

        Object obj = JSONValue.parse(jsonString);
        JSONObject jsonObject = (JSONObject) obj;
        String name = (String) jsonObject.get("Full Name");
        double fees = (Double) jsonObject.get("Tuition Fees");
        long rollNo = (Long) jsonObject.get("Roll No.");

        System.out.println(name + " " + fees + " " + rollNo);
    }
}

Output:

ReadJson
Snapshot of JavaJsonDecoding.java File

Explanation:

  • JSONValue.parse() converts JSON text into a Java object
  • get() retrieves values using keys
  • Explicit casting is required for numeric types
Comment