DEV Community

CitronBrick
CitronBrick

Posted on • Edited on

JSON-B : An Introduction

The Java API for JSON Binding (JSON-B) is a JavaEE/JakartaEE specification (JSR-353) to convert Java objects to json & vice-versa. Apache Johnzon is an implementation of the JSON-B spec.

Javadoc

JSON-B is an alternative to GSON & Jackson.

Consider the following Java class (simplified)

class Task {
    String description;
    LocalDate deadline;
    boolean over;
}
Enter fullscreen mode Exit fullscreen mode

You can convert Task instances to json as follows:

Task task = new Task("Jump")
Jsonb jsonb = JsonbBuilder.create();
String taskJson = jsonb.toJson(task);
Enter fullscreen mode Exit fullscreen mode

{"deadline":"2021-10-15","description":"Jump","over":false}

Let's say I want to initialize a bunch of Task objects from fakerestapi.azurewebsites.net. It provides a json web-service for activities with the following schema :

Activity schema: id title dueDate completed

To convert this json objects of this schema to Activity instances, you can use the @JsonbProperty annotation.

class Task {
    @JsonbProperty("title")
    String description;

    @JsonbProperty("dueDate")
    LocalDate deadline;

    @JsonbDateFormat(JsonbDateFormat.DEFAULT_FORMAT)
    @JsonbProperty("completed")
    boolean over;

    @JsonbNillable
    // creator can be optionally present in json
    String creator; 
}
Enter fullscreen mode Exit fullscreen mode

Properties that can be optionally present/absent in the json, must be annotated with @JsonbNillable

Suppose you have multiple sources of Activities each with their own schema you can create & use JsonbAdapters.

@JsonbTypeAdapter
class GermanTaskAdapter implements JsonbAdapter<Task, JsonObject> {

    public Task adaptFromJson(JsonObject jo) {
       var description = jo.getString("Titel");
       var deadline = LocalDate.parse(jo.getString("Stichtag"));
       var over = jo.getBoolean("vollendet");
       return new Task(description, deadline, over);
    }

    public JsonObject adaptToJson(Task task) {
       return Json.createObjectBuilder()
           .add("id", 0)
           .add("Titel", task.getTitle())
           .add("Stichtag", task.getDeadline().toString())
           .add("vollendet", task.isOver())
    }
}
Enter fullscreen mode Exit fullscreen mode

You can have multiple adapters for a domain class, through which you can consume from multiple sources & provide multiple json implementations.

In the above adapter, I have used the *Java API for JSON Processing
*
JSON-P API to create and use JsonObject instances.

If you are using Spring there is JsonbHttpMessageConverter since version 5.

This is my first online technical article (was unpublished for a looong time). Questions & Feedback welcome.
Thanks for reading.

Top comments (0)