How to conditionally ignore properties with a Jackson AnnotationIntrospector

此生再无相见时 提交于 2019-12-20 02:46:14

问题


I want to create an annotation to make Jackson ignore the annotated fields unless a certain tracing level is set:

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

Or, if this is easier to implement, I could also have separate annotations for the different levels:

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

Depending on the configuration of the ObjectMapper, either

  • all "Debug" and "Info" fields shall be ignored when serializing and deserializing, or
  • all "Debug" fields shall be ignored, or
  • all fields shall be serialized/deserialized.

I suppose that this should be possible with a custom AnnotationIntrospector. I have this post, but it doesn't show an example of how to implement a custom AnnotationIntrospector.


回答1:


If you want to sub-class JacksonAnnotationIntrospector, you just need to override hasIgnoreMarker, something like:

@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();
}

but note that annotation introspection only occurs once per class so you can not dynamically change the criteria you use.

For more dynamic filtering you may want to rather use JSON Filter functionality, see for example: http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html



来源:https://stackoverflow.com/questions/29020408/how-to-conditionally-ignore-properties-with-a-jackson-annotationintrospector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!