jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

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

Open hjohn opened this issue 3 years ago • 10 comments

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.

hjohn avatar Oct 16 '22 18:10 hjohn