Fundhor
Fundhor

Reputation: 3577

How to use latest SequencedSet interface (java21) with jackson?

I have a class with a SequencedSet field, but I can't find a way to make it work with jackson deserialization.

class MyClass {
    private SequencedSet<UUID> ids;

    public SequencedSet<UUID> getIds() {
        return ids;
    }

    public void setIds(SequencedSet<UUID> ids) {
        this.ids = ids;
    }
}

I get this error

InvalidDefinition Cannot find a deserializer for non-concrete Collection type [collection type; class java.util.SequencedSet, contains [simple type, class java.util.UUID]]

Edit: I defaulted to using LinkedHashSet instead of SequencedSet

Upvotes: 1

Views: 405

Answers (2)

samabcde
samabcde

Reputation: 8114

This is supported in jackson 2.16.0, but as of spring-boot-starter-json 3.2.4, it is still depending on 2.15.4 .

If upgrading to >2.16 is not an option, we could:

1. configure ObjectMapper the implementation to use, referring to this answer

    SimpleModule module = new SimpleModule("SequencedCollectionModule", Version.unknownVersion());
    SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver();
    resolver.addMapping(SequencedSet.class, LinkedHashSet.class);
    module.setAbstractTypes(resolver);
    objectMapper.registerModule(module);

2. using JsonDeserialize annotation to specify which implementation to use for deserialization.

class MyClass {
    @JsonDeserialize(as = LinkedHashSet.class)
    private SequencedSet<UUID> ids;

    public SequencedSet<UUID> getIds() {
        return ids;
    }

    public void setIds(SequencedSet<UUID> ids) {
        this.ids = ids;
    }
}

Upvotes: 0

Markus Heiden
Markus Heiden

Reputation: 11

As a workaround I made just the setter using LinkedHashSet. Then at least the field and the getter may use SequencedSet.

class MyClass {
    private SequencedSet<UUID> ids;

    public SequencedSet<UUID> getIds() {
        return ids;
    }

    public void setIds(LinkedHashSet<UUID> ids) {
        this.ids = ids;
    }
}

This requires (de)serialization via getters/setters (or constructors) instead of direct field access though.

To the question in the comments which implementation I expected: LinkedHashSet or similar because that preserves the properties of a SequencedSet: The order is preserved and no duplicates are allowed. For Set and List Jackson automatically selects concrete implementations too.

Upvotes: 0

Related Questions