问题描述
我想创建一个注释,让 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
的配置,要么
- 在序列化和反序列化时应忽略所有调试"和信息"字段,或
- 应忽略所有调试"字段,或
- 所有字段都应序列化/反序列化.
我想这应该可以通过自定义 AnnotationIntrospector
.我有这个 post,但它没有展示如何实现自定义 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 有条件地忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!