4

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.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Abdull
  • 26,371
  • 26
  • 130
  • 172

1 Answers1

6

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 {
    
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • Awesome, I went with the option *`@JsonIgnoreProperties(..)` on the JPA entity class level*. I find it to be the cleanest solution, as it keeps this serialization aspect cohesive to the serialization-centric class. – Abdull May 09 '17 at 12:24