Enterprise Java

Get to Know Custom De/Serializers: JSON Binding Overview Series

The most advanced way to customize JSON Binding is with custom serializers and deserializers.

JSON-B serializers and deserializers are the lowest level of customisation available and give access to the JSON Processing parsers and generators.

A custom serializer must implement the JsonbSerializer interface and provide logic for the serialise() method. This code shows a simple example of how to customise the serialisation of the a Book object.

The JsonGenerator is used to create a JSON document property by property. The value of the id property is fixed and the author’s name is flattered to the firstName and lastName property.

public class BookSerializer implements JsonbSerializer<Book> {

    @Override
    public void serialize(Book book,
             JsonGenerator generator, SerializationContext ctx) {
        generator.writeStartObject();
        generator.write("id", "QWE-123-RTS");
        generator.write("title", book.getTitle());
        generator.write("firstName", book.getAuthor().split(" ")[0]);
        generator.write("lastName", book.getAuthor().split(" ")[1]);
        generator.writeEnd();
    }

}

The deserialization operation is customized by implementing the JsonbDeserializer interface and providing logic for the deserialize() method.

This code shows an example which extracts just the Book’s id from the JSON document.

public class BookDeserializer implements JsonbDeserializer<String> {
    @Override
    public String deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            if (event == JsonParser.Event.KEY_NAME) {
                String keyName = parser.getString();
                if (keyName.equals("id")) {
                    return ctx.deserialize(String.class, parser);
                }
            }
            parser.next();
        }
        return "";
    }
}

Instances of the serializer and deserializer are registered with a JsonbConfig via the appropriate .withDeserializers() or .withSerializers() method as shown here.

JsonbConfig config = new JsonbConfig()
    .withDeserializers(new BookDeserializer())
    .withSerializers(new BookSerializer());

Alternatively, the type can be annotated with @JsonbTypeSerializer or @JsonbTypeDeserializer and passed the class name of the relevant customisation class.

@JsonbTypeDeserializer(BookDeserializer.class)
public class Booklet{}

Round-up

So we have seen today some exciting new changes in the way Java EE processes JSON.

JSON Processing is now up to date with the latest internet standards and the JSON-B’s designers have set out to standardize the way developers transform Java objects to JSON documents and vice versa.

If the API and features you’ve seen so far seem familiar to you, that is intentional:  the API standardizes serialization and deserialization techniques that should be already familiar to most Java developers.

The two customisation models: runtime and compile time offer a highly flexible and intuitive way to fine tune the API.

The self-describing annotations and configuration methods contribute towards productivity and ease development.

Even so, lower-level manipulation of the serialization and deserialization operations and advanced customisation are easily achieved.

There is plenty more to know about the JSON Binding API than what I talk about in these blog posts.

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Get to Know Custom De/Serializers: JSON Binding Overview Series

Opinions expressed by Java Code Geeks contributors are their own.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button