Why can’t Jackson deserialize single field class with RequiredArgsConstructor?

Viewed 756

If I have a class using Lombok:

@RequiredArgsConstructor
@Getter
class Example {
  private final String id;
}

And try to deserialize it from

{
  “id”: “test”
}

Jackson throws an exception that although at least one creator was provided, it could not deserialize.

If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.

Does anyone know what’s going on here? Why are you unable to deserialize if you only have one field?

1 Answers

When only way to intialize object properties is through contructor, Jackson needs to be told that deserialization should happen using constructor via @JsonCreator annotation.

Also, all the property names should be provided via @JsonProperty annotation because Jackson needs to know the sequence of attributes passed in contructor to correctly map json values to Java object attributes.

So, if you are not using lombok contructor, then constructor will look like

    @JsonCreator
    public Example (@JsonProperty("id") String id) {
        this.id = id;
    }

If you don't want to manually write the contructor, go ahead with @tashkhisi's answer.

Also, I highly doubt following could happen. Could you update the question with code showing this?

If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.

Related