AnnotationIntrospector

AnnotationIntrospector

本文介绍了如何使用Jackson AnnotationIntrospector有条件地忽略属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非要设置特定的跟踪级别,否则我想创建一个注释以使Jackson忽略带注释的字段:

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;
}

取决于ObjectMapper的配置,

    序列化和反序列化时,
  • 所有调试"和信息"字段都将被忽略,或者
  • 所有调试"字段都将被忽略,或者
  • 所有字段均应序列化/反序列化.
  • 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.

我认为使用自定义 AnnotationIntrospector 应该可以实现.我有此帖子,但未显示有关如何实现自定义AnnotationIntrospector的示例.

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.

推荐答案

如果要对JacksonAnnotationIntrospector进行子类化,则只需要覆盖hasIgnoreMarker,就像这样:

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.

有关更多动态过滤,您可能希望使用JSON过滤器功能,例如: http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html

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

这篇关于如何使用Jackson AnnotationIntrospector有条件地忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 15:10