I have an interface with a default method:
public interface Book {
String getTitle();
default String getSentenceForTitle() {
return "This book's title is " + getTitle();
}
}
... and I have an JPA @Entity
implementing this interface:
@Entity
public class JpaBook implements Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
// ...
@Override
public String getTitle() {
return title;
}
}
Using this entity, I noticed that Jackson will also serialize the default method getSentenceForTitle()
- though in my particular case, I don't want sentenceForTitle
to be serialized.
Is there a way of letting Jackson know that I don't want to have a default methods serialized, yet keep that method's behavior? The current workaround I came up with is overriding the default method, annotating it with @JsonIgnore
, and delegating to the default method:
@Entity
public class JpaBook implements Book {
// ...
@Override
@JsonIgnore
public String getSentenceForTitle() {
return Book.super.getSentenceForTitle();
}
}
But this solution can get quite verbose and error-prone for interfaces with many default methods.