簡體   English   中英

如何使用Jackson AnnotationIntrospector有條件地忽略屬性

[英]How to conditionally ignore properties with a Jackson AnnotationIntrospector

我想創建一個注釋,使傑克遜忽略帶注釋的字段,除非設置了某個跟蹤級別:

public class A {
    @IgnoreLevel("Debug") String str1;
    @IgnoreLevel("Info") String str2;
}

或者,如果這更容易實現,我也可以為不同級別分別添加注釋:

public class A {
    @Debug String str1;
    @Info String str2;
}

根據ObjectMapper的配置,也可以

  • 序列化和反序列化時,應忽略所有“Debug”和“Info”字段,或
  • 所有“調試”字段都應該被忽略,或者
  • 所有字段都應序列化/反序列化。

我想這應該可以使用自定義AnnotationIntrospector 我有這篇文章 ,但它沒有顯示如何實現自定義AnnotationIntrospector的示例。

如果你想要子類JacksonAnnotationIntrospector ,你只需要覆蓋hasIgnoreMarker ,例如:

@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
  IgnoreLevel lvl = m.findAnnotation(IgnoreLevel.class);
  // use whatever logic necessary
  if (level.value().equals("Debug")) return true;
  return super.hasIgnoreMarker();
}

但請注意,注釋內省僅在每個類中出現一次,因此您無法動態更改所使用的條件。

要獲得更多動態過濾,您可能需要使用JSON過濾器功能,例如,請參閱: http//www.cowtowncoder.com/blog/archives/2011/09/entry_461.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM