2017-05-05 137 views
1

我有一个默认的方法的接口:杰克逊@JsonIgnore继承的Java 8默认方法

public interface Book { 

    String getTitle(); 

    default String getSentenceForTitle() { 
     return "This book's title is " + getTitle(); 
    } 

} 

...我有一个JPA @Entity实现了这个接口:

@Entity 
public class JpaBook implements Book { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    private String title; 

    // ... 

    @Override 
    public String getTitle() { 
     return title; 
    } 

} 

使用此实体,我注意到杰克逊也将序列化默认方法getSentenceForTitle() - 虽然在我的特殊情况下,我不想sentenceForTitle被序列化。

有没有让杰克逊知道我不想有一个默认方法序列化,但保持该方法的行为?目前的解决方法,我想出了压倒一切的默认方法,用@JsonIgnore注释它,并委托给默认的方法:

@Entity 
public class JpaBook implements Book { 

    // ... 

    @Override 
    @JsonIgnore 
    public String getSentenceForTitle() { 
     return Book.super.getSentenceForTitle(); 
    } 

} 

但是这种解决方案可以得到相当繁琐,容易出错的接口有许多默认的方法。

回答

2

为了让特定的方法/字段被忽略,必须以某种方式指定它,而注解是最简单的方法。我可以推荐比你试过这么简单以下选项:

  1. 标注的默认方法没有JpaBook覆盖它。因此,在Book

    @JsonIgnore 
    default String getSentenceForTitle() { 
        return "This book's title is " + getTitle(); 
    } 
    
  2. 如果Book是不是你的控制之下,或者如果有你想方便地指定字段列表,你可以离开Book,因为它是与现场或阵列标注JpaBook的领域忽略。 E.g:

    @JsonIgnoreProperties("sentenceForTitle") 
    class JpaBook implements Book { 
    

    或者

    @JsonIgnoreProperties({"sentenceForTitle", "alsoIgnoreThisField"}) 
    class JpaBook implements Book { 
    
  3. 您也可以标注JpaBook序列化(的JpaBook)各个领域和忽略所有干将。你不需要在Book E.g做任何事情:

    @JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE) 
    class JpaBook implements Book { 
    
+0

真棒,我选择去*'@ JsonIgnoreProperties(..)'在JPA实体类水平*。我发现它是最干净的解决方案,因为它使序列化方面与以序列化为中心的类保持一致。 – Abdull