Jackson vs. Gson vs. JSON-B | Custom Object Instantiation (args constructor, factory method) for JSON in Java

In this article we will compare custom object creation capabilities (such as Multi args constructor, static factory method) of JSON binding libraries in java i.e. Jackson vs. Gson vs. JSON-B (Eclipse Yasson)

For complete comparison of top JSON libraries & their features, visit below article.

Jackson vs. Gson vs. JSON-B vs. JSON-P vs. org.JSON vs. Jsonpath | Java JSON libraries features comparison

Lets take example of Employee object which has –

  1. Multiple argument constructor for properties & no setter for properties i.e. only getters.
  2. Public static factory method for creating instance & private default constructor.

Jackson

In jackson, for both cases, we can mark constructor or factory method with annotation as shown below to notify Jackson to use multi args constructor to instantiate Employee object.

Args constructor annotated with @JsonCreator

Factory method annotated with @JsonCreator

Parse JSON using both above POJOs in jackson.



GSON

Lets take same employee example as above. GSON does not have any specific out of the box annotation for this. But by default, GSON ignores constructor in such cases & uses reflection to instantiate object. This might be problematic as you might not notice this & assume constructor is being used.

You can specifically write custom JsonDeserializer to achieve the same.



JSON-B

JSONB does have annotations similar to Jackson as shown below. JSON-B annotation support both argument constructor as well as public static factory methods for instance creation.

Args constructor annotated with @JsonbCreator

Factory method annotated with @JsonbCreator

Now lets parse JSON using above both POJOs in JSONB.



Leave a Reply

Your email address will not be published. Required fields are marked *