79238975

Date: 2024-11-30 07:05:19
Score: 0.5
Natty:
Report link

This way, we’ll have all the object’s fields initialized at the moment of creation. Final modifiers in fields’ declaration won’t let us change their values in future. To make this object deserializable, we simply need to add a couple of annotations to this constructor:

  @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) {
    this.id = id;
    this.name = name;
}

Let’s take a closer look at the annotations we have just added.

First of all, @JsonCreator tells Jackson deserializer to use the designated constructor for deserialization.

There are two modes that can be used as a parameter for this annotation – PROPERTIES and DELEGATING. PROPERTIES is the most suitable when we declare an all-arguments constructor, while DELEGATING may be useful for single-argument constructors.

After that, we need to annotate each of constructor arguments with @JsonProperty stating the name of the respective property as the annotation value. We should be very careful at this step, as all the property names must match with the ones that we used during serialization.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @JsonCreator
  • User mentioned (0): @JsonProperty
  • Low reputation (1):
Posted by: 刚刚好