News Ticker

Get to Know Custom Object Creation: JSON Binding Overview Series

Let’s take a look at how JSON Binding handles custom object creation.

Next article in this series covers customization of JSON-B with adapters.

JSON-B expects all classes to have a public no-argument constructor, which it uses during deserialization to instantiate the target class. Once the instance is created, it is populated with data from the JSON document by calling the appropriate setter method or by directly setting the public field.

However, sometimes this is not sufficient, especially when construction is complex, and for these cases, a custom constructor or static factory method must be implemented. This code snippet shows an implementation of a custom constructor.

public class Magazine {
    private String title;
    private Author authorName;

    public Magazine(@JsonbProperty("bookTitle") String title,
                    @JsonbProperty("firstName") String firstName,
                    @JsonbProperty("surname") String lastName) {
        this.title = title;
       this.authorName = new Author(firstName, lastName);

You will notice the use of the JsonbProperty annotation to map JSON property names to the parameters in the constructor parameter list and how the constructor uses the firstname and lastname to construct an instance of the Author class.

This JSON document is successfully deserialized to the Magazine class.

  "firstName": "Alex",
  "surname": "Theedom",
  "bookTitle": "Fun with JSON-B"

For a more sophisticated customization of the serialization and deserialization process, we need to take a look at how adapters function and that’s what I will do next.

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

%d bloggers like this: