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.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With