4

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?

Matt
  • 2,063
  • 1
  • 14
  • 35
  • Not sure if this really the problem, but in your example JSON you have "strange" double quotes. If I paste this JSON in a JSON-validator, then it gives me a parse error. If I correct the double quotes, then it parses fine. – Christoph Jun 10 '20 at 18:10
  • That’ll just be where I’ve typed the question out on mobile. It’s definitely the right quotes when testing. – Matt Jun 10 '20 at 18:31
  • are you sure it work -> If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.? – Tashkhisi Jun 10 '20 at 19:14

1 Answers1

0

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.

Smile
  • 3,832
  • 3
  • 25
  • 39
  • 1
    It is true adding an additional string field will fix the issue, Jackson has an issue with single field objects, see this github issue: https://github.com/FasterXML/jackson-databind/issues/1498 – Shane Aug 30 '21 at 13:54