Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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.

like image 742
Elad Benda Avatar asked Mar 12 '15 21:03

Elad Benda


People also ask

How do you ignore fields in Jackson?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do you ignore certain fields based on a serializing object to JSON?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.

How do I ignore JSON property?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

How do I ignore properties in spring boot?

Use that annotation at the top of the whole class like so: @JsonIgnoreProperties({"password"}) public class Employee { private String id; private String lastName; private String firstName; private String password; ... If you need to ignore multiple properties, separate them with a comma inside the curly braces.


1 Answers

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

like image 103
StaxMan Avatar answered Oct 22 '22 17:10

StaxMan