Enterprise Java

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.

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Get to Know Custom Object Creation: 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.
Notify of

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

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
6 years ago

I’d presume you have to (or ought to) follow the bean pattern for defining JSON mapped classes?

Back to top button