Understanding of deserialisation of Jackson (fasterxml)

352 views Asked by At
How does Jackson deserialisation work when creating a Java object from JSON?

A common conception is that it first calls the No Argument Constructor and then proceeds to call setters.

But,

  • What happens if there is no No Argument Constructor?
  • Can Jackson be asked to choose some other constructor?
  • Is there any issue with Boilerplate code generators like Lombok?
1

There are 1 answers

3
Anant Simran Singh On

Simply put, Jackson first calls a constructor to instantiate an object and then proceeds to call setters on remaining fields.

Now, how does it decide which constructor to call and what are the remaining fields?

  • If there are no special annotations defined on a constructor, Jackson will always look for No Argument Constructor. We will come on special annotations shortly. If the Jackson does not find a No Argument constructor, it will throw an error.
  • Since fasterxml 2.7, Jackson also looks for @ConstructorProperties annotation. In case of multiple constructors having this annotation, it will choose the one with maximum arguments. For the rest of the fields, it calls their setter.
  • You can also use @JsonCreator to call a specific constructor. But @ConstructorProperties will still interfere with it. Even though @JsonCreator can be used on a single constructor, @ConstructorProperties can be used on many.
  • Lombok annotates its All Args Constructor with @ConstructorProperties annotation. So that might interfere with default Jackson working as well.