News Ticker

Get to Know Adapters: JSON Binding Overview Series

An adapter configures custom object creation and serialization by implementing the JsonbAdapter interface. The methods adaptToJson() and adaptFromJson() are overwritten with logic that performs the serialization and deserialization operation.

The next article is about the most advanced way to customize JSON-B with custom serializers and deserializers.

In the example implementation here, the adaptToJson() method has been implemented with code that transforms the Booklet object into a JsonObject using the JSON object builder from the JSON Processing API. The adaptFromJson() method constructs a Booklet object from a JsonObject instance.

public class BookletAdapter implements JsonbAdapter<Booklet, JsonObject> {

    @Override
    public JsonObject adaptToJson(Booklet booklet) {
        return Json.createObjectBuilder()
           .add("title", booklet.getTitle())
           .add("firstName", booklet.getAuthor().getFirstName())
           .add("lastName", booklet.getAuthor().getLastName())
           .build();
    }

    @Override
    public Booklet adaptFromJson(JsonObject json) {
        Booklet booklet = new Booklet(json.getString("title"),
        new Author(json.getString("firstName"),
        json.getString("lastName")));
        return booklet;
    }
}

As you can see, the adaptToJson() method flattens the Author object to two properties: firstName and lastNameThe adaptFromJson() method reconstructs the Author object and outputs a Booklet instance.

The JsonbAdapter is very flexible and can be used to customize the serialization and deserialization of individual fields, as well as entire objects.

This is achieved by marking the field, method or class that should be customized with the JsonbTypeAdapter annotation and passing it the class name of the JsonbAdapter to use.

An example implementation is shown here. The firstName field is marked with the JsonbTypeAdapter annotation and the FirstNameAdapter class specified as the adapter.

public class Author {
    @JsonbTypeAdapter(FirstNameAdapter.class)
    private String firstName;
}

public class FirstNameAdapter implements JsonbAdapter<String, JsonValue> {

    @Override
    public JsonValue adaptToJson(String fullName) {
        return Json.createValue(fullName.subSequence(0, 1).toString());
    }

    @Override
    public String adaptFromJson(JsonValue json) {
        return json.toString();
    }

}

And finally, the most advanced way to customize JSON-B with custom serializers and deserializers.

There is plenty more to know about the JSON Binding API than what I talk about in these blog posts and in my new book Java EE 8: Only What’s New, I cover this API in much more detail.

Other Interesting Articles

Leave a Reply

Discover more from Digital Transformation and Java Video Training

Subscribe now to keep reading and get access to the full archive.

Continue reading