Skip to content

Serializing a Java 16 Record includes transient data from getters from implemented interfaces #3628

@hjohn

Description

@hjohn

This may be by design, but I think it may be a bug...

Describe the bug
When serializing a record that implements an interface, Jackson also serializes any values resulting from getters in an implemented interface. Such additional "getters" should however always be perceived as transient, as they cannot influence the actual data stored in the record.

For example:

public sealed interface StreamMetaDataEvent extends AggregateEvent {
  public record Updated(StreamMetaData streamMetaData) implements StreamMetaDataEvent {
    @Override
    public Type getType() {
      return Type.FULL;
    }

    @Override
    public String getAggregateId() {
      return "" + streamMetaData.contentId().asInt();
    }
  }

  public record Removed(ContentID id) implements StreamMetaDataEvent {
    @Override
    public Type getType() {
      return Type.DELETE;
    }

    @Override
    public String getAggregateId() {
      return "" + id.asInt();
    }
  }
}

The getters here are transient (they contain no new information) and are coming from the AggregateEvent interface:

public interface AggregateEvent {
  enum Type { FULL, DELETE }

  Type getType();
  String getAggregateId();
}

Work around

Configuring setVisibility(PropertyAccessor.GETTER, Visibility.NONE) will also ignore the records fields (not sure if they should be considered "getters", but I suppose they might). Configuring in addition setVisibility(PropertyAccessor.FIELD, Visibility.ANY) resolves the issue.

Version information
Which Jackson version(s) was this for? 2.13.4

Expected behavior
I would expect Jackson to recognize records, and recognize that it is fully defined by the records fields; any additional methods, getters or otherwise, should be considered irrelevant for reconstructing the record.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions