Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson @JsonIgnore an inherited Java 8 default method

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.

like image 891
Abdull Avatar asked Sep 16 '25 10:09

Abdull


1 Answers

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:

  1. Annotate the default method without overriding it in JpaBook. So in Book:

    @JsonIgnore
    default String getSentenceForTitle() {
        return "This book's title is " + getTitle();
    }
    
  2. 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 {
    
  3. 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 {
    
like image 77
Manos Nikolaidis Avatar answered Sep 18 '25 09:09

Manos Nikolaidis