Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is use of @JsonCreator necessary when using @JsonProperty?

Tags:

java

jackson

I am using Jackson @JsonProperty(name) annotation on a parameter to a constructor and every document I came across pointed that we must use the @JsonCreator annotation with @JsonProperty for it to work properly but even without the @JsonCreator annotation, my code works fine then what is the use of @JsonCreator

public TestClass(@JsonProperty("name") Map<String, String> data) {
    this.name = name;
}

public Map<String, String> getName() {
    return name;
}

The above code works fine even without the @JsonCreator Annotation.

like image 784
riddler0212 Avatar asked Dec 05 '22 16:12

riddler0212


2 Answers

Jackson has to know in what order to pass fields from a JSON object to the constructor. Because you have a single argument constructor, the creation works without @JsonCreator

From javadoc

Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

NOTE: when annotating creator methods (constructors, factory methods), method must either be:

Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

like image 146
sidgate Avatar answered Feb 23 '23 15:02

sidgate


Newer versions of Jackson also do consider the case where all parameters have explicit @JsonProperty, to remove the need for separate @JsonCreator. It may be the case that Javadocs have not been updated to explain this special case.

Note that special case of single String / int / long / boolean argument is slightly different, because while that would be detected as well (for public constructor), it be "Delegating" creator and only match if the whole incoming value is of matching JSON type (JSON String, Number or Boolean, respectively).

like image 42
StaxMan Avatar answered Feb 23 '23 13:02

StaxMan