简体   繁体   English

如何使用Jackson AnnotationIntrospector有条件地忽略属性

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

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 根据ObjectMapper的配置,也可以

  • all "Debug" and "Info" fields shall be ignored when serializing and deserializing, or 序列化和反序列化时,应忽略所有“Debug”和“Info”字段,或
  • all "Debug" fields shall be ignored, or 所有“调试”字段都应该被忽略,或者
  • all fields shall be serialized/deserialized. 所有字段都应序列化/反序列化。

I suppose that this should be possible with a custom AnnotationIntrospector . 我想这应该可以使用自定义AnnotationIntrospector I have this post , but it doesn't show an example of how to implement a custom AnnotationIntrospector . 我有这篇文章 ,但它没有显示如何实现自定义AnnotationIntrospector的示例。

If you want to sub-class JacksonAnnotationIntrospector , you just need to override hasIgnoreMarker , something like: 如果你想要子类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();
}

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 要获得更多动态过滤,您可能需要使用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