From Java Object to JSON and Back with Jakarta JSON Binding (JSON-B)

To use JSON-B (Jakarta JSON Binding) directly with a Java SE app, like e.g. JUnit, you will need to declare a single dependency:


Now a Java class:

import java.util.Date;

public class Workshop {
    public String title;
    public Date date;
    public String description;


...can be serialized and deserialized with JSON-B:


import airhacks.workshops.entity.Workshop;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;

public interface Mapper {
    final static String FILE = "workshops.json";

    static void save(Workshop workshop) {
        var jsonb = JsonbBuilder.create(new JsonbConfig().withFormatting(true));
        try (var writer = new FileWriter(FILE)) {
            jsonb.toJson(workshop, writer);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);

    static Workshop load() {
        try (var reader = new FileReader(FILE)) {
            return JsonbBuilder.create().fromJson(reader, Workshop.class);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
} a JUnit test:

import java.util.Date;

import org.junit.jupiter.api.Test;

public class JSONBTest {

    public void serializeThenDeserialize() {
        var workshop = new Workshop(); = new Date();
        workshop.description = "no slides";
        workshop.title = "java and jakarta";;

        var copy = Mapper.load();
        assertEquals(workshop.title, copy.title);


...and the content of the workshops.json is:

    "date": "2021-10-03T05:25:42.168Z[UTC]",
    "description": "no slides",
    "title": "java and jakarta"


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments