【问题标题】:How to conditionally ignore properties with a Jackson AnnotationIntrospector如何使用 Jackson AnnotationIntrospector 有条件地忽略属性
【发布时间】:2015-03-12 21:21:04
【问题描述】:

我想创建一个注释,让 Jackson 忽略带注释的字段,除非设置了某个跟踪级别:

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

或者,如果这更容易实现,我还可以为不同级别设置单独的注释:

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

取决于ObjectMapper的配置,要么

  • 序列化和反序列化时应忽略所有“调试”和“信息”字段,或者
  • 应忽略所有“调试”字段,或
  • 所有字段都应序列化/反序列化。

我想这应该可以通过自定义AnnotationIntrospector 实现。我有这个post,但它没有显示如何实现自定义AnnotationIntrospector 的示例。

【问题讨论】:

    标签: java json annotations jackson annotation-introspector


    【解决方案1】:

    如果你想继承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

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 2013-03-24
      • 2019-02-22
      • 2015-01-12
      • 2014-06-13
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多