Skip to content

immutable classes with @JsonIdentityInfo can be deserialized; records cannot #5238

@clo-vis

Description

@clo-vis

Search before asking

  • I searched in the issues and found nothing similar.

Describe the bug

If @JsonIdentityInfo is used with records, an exception is thrown at deserialization.

Version Information

2.19.2

Reproduction

This works perfectly:

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
    public static void main(String args[]) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Thing thing1 = new Thing(1, "name1");
        Thing thing3 = new Thing(3, "name3");
        Example example = new Example(List.of(thing1, thing3), thing3);

        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(example);
        System.out.println(jsonString);
        Example exampleD = mapper.readValue(jsonString, Example.class);
        System.out.println(exampleD);
    }
}

record Example(List<Thing> allThings, Thing selected) {}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
// record Thing(int id, String name) { }
class Thing {
    public final int id;
    public final String name;

    @JsonCreator
    Thing(@JsonProperty("id") int id, @JsonProperty("name") String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Thing [id=" + id + ", name=" + name + "]";
    }
}

If, however, I replace class Thing {...} with record Thing(int id, String name) { }, an exception is thrown when the json is deserialized:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No fallback setter/field defined for creator property 'id' (of Thing) (through reference chain: Example["allThings"]->java.util.ArrayList[0])

Expected behavior

Either no exception when using records or a more informative error message if records cannot be supported for whatever reason.

Additional context

See #3307 - marked with try-with-later-jackson.

(I tried with the last available version.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    RecordIssue related to JDK17 java.lang.Record supportto-evaluateIssue that has been received but not yet evaluated

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions