Support Online
Skip to main content

Java JSON Processing Guide: Reading, Writing and Parsing

🧠 What Will You Learn in This Guide?

This guide walks you through the JSR 353 (Java JSON Processing API) standard used to process JSON (JavaScript Object Notation) data in Java.
You will learn how to read JSON data into a Java object (JsonReader), create JSON from a Java object (JsonWriter), and stream-based parsing (JsonParser).

You'll also see techniques for processing JSON data without keeping it in memory (Streaming API) and easily creating small objects (Object Model API).

⚙️ Java and JSON Processing (JSR 353)

JSON is a lightweight human-readable data format consisting of key-value pairs.
It is preferred in web services and API responses because it is more compact than XML.

With the JSR 353 standard, Java provides two models for processing JSON data:

API TypeDescription
Object Model APISuitable for small JSON data. It loads all JSON into memory, providing a DOM-like structure. (JsonReader, JsonObject)
Streaming APIIdeal for large JSON data. It works event-driven and uses memory efficiently. (JsonParser, JsonGenerator)

🧩 Maven Dependency

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.2</version>
</dependency>

💬 Note: This library is already included in GlassFish 4.0 and above.


📥 Step 1: Reading JSON Data into Java Object (JsonReader)

In this example, we will read the data in the file named calisan.json and convert it to an Employee object.

Sample JSON Data (calisan.json)


{
"id": 404,
"adSoyad": "GenixNode Yılmaz",
"calismaDurumu": true,
"adres": {
"sokak": "Teknoloji Caddesi",
"sehir": "Ankara",
"postaKodu": 6000
},
"telefonlar": [5321112233, 5459998877],
"gorev": "Teknik Yazar"
}

Read Code


import java.io.FileInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class CalisanJSONOkuyucu {

public static final String JSON_FILE = "calisan.json";

public static void main(String[] args) throws Exception {
InputStream girisAkimi = new FileInputStream(JSON_FILE);
JsonReader jsonOkuyucu = Json.createReader(girisAkimi);

JsonObject jsonNesne = jsonOkuyucu.readObject();

jsonOkuyucu.close();
girisAkimi.close();

Employee calisan = new Employee();
calisan.setId(jsonNesne.getInt("id"));
calisan.setName(jsonNesne.getString("adSoyad"));
calisan.setRole(jsonNesne.getString("gorev"));

System.out.println(calisan);
}
}

💬 Description: JsonReader loads all JSON data into memory and accesses it as JsonObject. This method is suitable for small files.


📤 Step 2: Writing Java Object in JSON Format (JsonWriter)

Now we will create an Employee object, convert it to JSON format and write it to the file.


import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

public class CalisanJSONYazici {

public static void main(String[] args) throws Exception {

JsonObject adres = Json.createObjectBuilder()
.add("sokak", "Bulut Sk.")
.add("sehir", "İstanbul")
.add("postaKodu", 34000)
.build();

JsonObject calisan = Json.createObjectBuilder()
.add("id", 100)
.add("adSoyad", "Deniz")
.add("calismaDurumu", false)
.add("gorev", "Müdür")
.add("telefonlar", Json.createArrayBuilder().add(123456).add(987654))
.add("adres", adres)
.build();

OutputStream cikis = new FileOutputStream("yeni_calisan.json");
JsonWriter yazici = Json.createWriter(cikis);
yazici.writeObject(calisan);
yazici.close();

System.out.println("JSON dosyası başarıyla oluşturuldu!");
}
}

💬 Description: JsonObjectBuilder and JsonArrayBuilder classes make it easy to create nested JSON structure with Builder Pattern.


🔍 Step 3: Parsing JSON with Flow Model (JsonParser)

For large JSON files, event-driven parsing is preferred instead of loading the entire data into memory.


import java.io.FileInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

public class CalisanJSONAyristirici {

public static void main(String[] args) throws Exception {
InputStream giris = new FileInputStream("calisan.json");
JsonParser parser = Json.createParser(giris);

String anahtar = null;
while (parser.hasNext()) {
Event olay = parser.next();
switch (olay) {
case KEY_NAME:
anahtar = parser.getString();
break;
case VALUE_STRING:
System.out.println(anahtar + ": " + parser.getString());
break;
case VALUE_NUMBER:
System.out.println(anahtar + ": " + parser.getLong());
break;
default:
// diğer event tipleri
}
}

parser.close();
giris.close();
}
}

💬 Description: JsonParser works event-based. Each KEY_NAME – VALUE_* pair is processed and large objects are not kept in memory.


📚 JSON API Classes Summary

ClassDescription
JsonReaderIt is used to read JSON data as an object.
JsonWriterIt is used to write Java object to JSON file.
JsonParserProvides stream-based parsing on large files.
JsonGeneratorIt generates JSON output step by step.
JsonObjectRepresents a JSON object.
JsonArrayRepresents JSON arrays.

❓ Frequently Asked Questions (FAQ)

  1. What is the difference between JSON-P and JSON-B?

JSON-P (Processing) is a low-level API; JSON-B (Binding) automatically converts Java objects to JSON.

  1. Why should I use JsonParser instead of JsonReader?

JsonParser is preferred to optimize memory for large files.

  1. Are there any other libraries for JSON processing in Java?

Yes: Jackson and Gson work like JSON-B and provide automatic conversion.

  1. Does JsonObject work like HashMap?

Yes, but JsonObject is an immutable structure, while HashMap is mutable.

  1. How do I validate JSON data?

You can validate with tools like JSONLint or use javax.json error trapping mechanisms.


🧩 Result

In this guide, you learned the basic building blocks of the Java JSON Processing API (JSR 353). You can now read, create, and parse JSON data in a stream-based manner.

🚀 Try your JSON processing skills on the GenixNode platform, test the high-performance Java infrastructure!