How to conditionally ignore properties using Jackson AnnotationIntrospector

I want to create an annotation so that Jackson ignores annotated fields if a specific trace level is not set:

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

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

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

Depending on the configuration of ObjectMapper , either

  • all Debug and Info fields should be ignored during serialization and deserialization, or
  • all Debug fields must be ignored, or
  • All fields must be serialized / deserialized.

I believe this should be possible with a custom AnnotationIntrospector . I have this post , but it does not show an example of how to implement a custom AnnotationIntrospector .

+3
source share
1 answer

If you want to subclass 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 happens once for each class, so you cannot dynamically change the criteria that you use.

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

+4
source

Source: https://habr.com/ru/post/1257454/


All Articles