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.
In order to have specific methods/fields ignored this has to be specified somehow and annotation is the simplest way to do that. I can recommend the following options that are simpler than what you have tried:
Annotate the default method without overriding it in JpaBook
. So in Book
:
@JsonIgnore
default String getSentenceForTitle() {
return "This book's title is " + getTitle();
}
If Book
isn't under your control or if there is a list of fields you want to conveniently specify, you can leave Book
as it is and annotate JpaBook
with a field or an array of fields to ignore. E.g:
@JsonIgnoreProperties("sentenceForTitle")
class JpaBook implements Book {
Or
@JsonIgnoreProperties({"sentenceForTitle", "alsoIgnoreThisField"})
class JpaBook implements Book {
You can also annotate JpaBook
to serialize all fields (of JpaBook
) and ignore all getters. You don't need to do anything at Book
E.g.:
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE)
class JpaBook implements Book {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With