Master Jakarta JSON API (JSON‑P & JSON‑B) with Simple Java Examples

This tutorial walks through using Jakarta JSON Processing and Binding APIs in a standalone Java application, demonstrating how to create, serialize, and deserialize JSON with JBang, complete with code samples and required dependencies.

JakartaEE China Community
JakartaEE China Community
JakartaEE China Community
Master Jakarta JSON API (JSON‑P & JSON‑B) with Simple Java Examples

This article shows how to use the Jakarta JSON Processing API (JSON‑P) and the Jakarta JSON Binding API (JSON‑B) in a simple monolithic Java application. It first introduces the two main APIs—Streaming API and Object Model API—explaining that the Object Model builds an in‑memory tree for random access while the Streaming API offers higher efficiency and lower memory usage.

Example 1: Creating a JSON Object

The first example uses JBang to run a Java class that builds a JSON object representing an order. The code imports jakarta.json.* classes, constructs the object with Json.createObjectBuilder(), adds fields such as orderId, orderDate, and nested objects for address and items, then pretty‑prints the result with a JsonWriter configured for PRETTY_PRINTING. The printed output shows the formatted JSON structure.

//usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS jakarta.json:jakarta.json-api:2.0.2
//DEPS org.glassfish:jakarta.json:2.0.1

import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonWriter;
import jakarta.json.stream.JsonGenerator;
import java.io.StringWriter;
import java.util.Collections;

public class JSONPrettyFormat {
    public static void main(String[] args) {
        JsonObject jsonObject = Json.createObjectBuilder()
            .add("orderId", 12345678)
            .add("orderDate", "2023-10-04")
            .add("orderStatus", "Pending")
            .add("orderDetails", Json.createObjectBuilder()
                .add("shippingAddress", Json.createObjectBuilder()
                    .add("street", "123 Main Street")
                    .add("city", "Anytown")
                    .add("state", "CA")
                    .add("zipCode", "90210")))
            .add("orderItems", Json.createArrayBuilder()
                .add(Json.createObjectBuilder()
                    .add("productId", 1002)
                    .add("productName", "Mouse")
                    .add("quantity", 1)
                    .add("unitPrice", 50)))
            .build();
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriterFactory(
            Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
            .createWriter(stringWriter);
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
        String formattedJson = stringWriter.toString();
        System.out.println("Formatted JSON:");
        System.out.println(formattedJson);
    }
}

The required Maven coordinates are jakarta.json:jakarta.json-api:2.0.2 for the API contract and org.glassfish:jakarta.json:2.0.1 for the implementation when running inside a Jakarta EE container.

Example 2: Serializing a Java Record to JSON (JSON‑B)

The second example demonstrates converting a Java record named Person into JSON using JSON‑B. After adding the dependencies jakarta.json.bind:jakarta.json.bind-api:3.0.0 and org.eclipse:yasson:3.0.3, the code creates a Person instance, builds a Jsonb object via JsonbBuilder.create(), and calls jsonb.toJson(person). The resulting JSON is printed, showing a straightforward mapping without needing extra annotations such as @JsonbProperty.

//usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS jakarta.json.bind:jakarta.json.bind-api:3.0.0
//DEPS org.eclipse:yasson:3.0.3

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbException;

public class JavaToJSON {
    public static void main(String[] args) throws Exception {
        try {
            Person person = new Person(12345678, "John", "Smith", "[email protected]", "+1234567890");
            Jsonb jsonb = JsonbBuilder.create();
            String serializedJson = jsonb.toJson(person);
            System.out.println("Serialized JSON:");
            System.out.println(serializedJson);
            jsonb.close();
        } catch (JsonbException e) {
            e.printStackTrace();
        }
    }
}

public record Person(int customerId, String firstName, String lastName, String email, String phone) {}

The Bind API coordinate is jakarta.json.bind:jakarta.json.bind-api:2.0.2 (API contract) and the implementation org.eclipse:yasson:3.0.3.

Example 3: Deserializing JSON to a Java Record (JSON‑B)

The third example reuses the same dependencies to read a JSON string and convert it back into a Person record. It creates a Jsonb instance, calls jsonb.fromJson(jsonString, Person.class), and prints each field of the resulting record, confirming successful deserialization.

//usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS jakarta.json.bind:jakarta.json.bind-api:3.0.0
//DEPS org.eclipse:yasson:3.0.3

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbException;

public class JSONToJava {
    public static void main(String[] args) throws Exception {
        String jsonString = """
        {
            "customerId": 12345678,
            "firstName": "John",
            "lastName": "Smith",
            "email": "[email protected]",
            "phone": "+1234567890"
        }""";
        try {
            Jsonb jsonb = JsonbBuilder.create();
            Person person = jsonb.fromJson(jsonString, Person.class);
            System.out.println("Customer ID: " + person.customerId());
            System.out.println("First Name: " + person.firstName());
            System.out.println("Last Name: " + person.lastName());
            System.out.println("Email: " + person.email());
            System.out.println("Phone: " + person.phone());
            jsonb.close();
        } catch (JsonbException e) {
            e.printStackTrace();
        }
    }
}

Running this code prints each attribute of the Person record, confirming that the JSON‑B API can seamlessly map between JSON strings and Java records.

Conclusion

Thanks to the user‑friendly design of the Jakarta JSON APIs, they can be integrated into ordinary Java applications with minimal friction. When combined with JBang, developers can quickly prototype JSON handling tasks—from basic object creation to complex serialization and deserialization—without heavyweight build tooling.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJBangJakarta JSONJSON-BJSON-PJSON processing
JakartaEE China Community
Written by

JakartaEE China Community

JakartaEE China Community, official website: jakarta.ee/zh/community/china; gitee.com/jakarta-ee-china; space.bilibili.com/518946941; reply "Join group" to get QR code

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.