Disable Jackson mapper for a particular annotation Disable Jackson mapper for a particular annotation json json

Disable Jackson mapper for a particular annotation


This the best I've come across. I think I saw it on the Jackson user group forums somewhere.

Essentially it makes a custom annotation introspector, which returns null if it sees that it has a specific annotation (in this case JsonTypeInfo)

JacksonAnnotationIntrospector ignoreJsonTypeInfoIntrospector = new JacksonAnnotationIntrospector() {            @Override            protected TypeResolverBuilder<?> _findTypeResolver(                    MapperConfig<?> config, Annotated ann, JavaType baseType) {                if (!ann.hasAnnotation(JsonTypeInfo.class)) {                    return super._findTypeResolver(config, ann, baseType);                }                return null;            }        };        mapper.setAnnotationIntrospector(ignoreJsonTypeInfoIntrospector);


I think it's a better idea to override findPropertiesToIgnore method like this:

    JacksonAnnotationIntrospector ignoreJsonTypeInfoIntrospector = new JacksonAnnotationIntrospector() {        @Override        public String[] findPropertiesToIgnore(AnnotatedClass ac) {            ArrayList<String> ret = new ArrayList<String>();            for (Method m : ac.getRawType().getMethods()) {                if(ReflectionUtils.isGetter(m)){                    if(m.getAnnotation(Transient.class) != null)                        ret.add(ReflectionUtils.getPropertyName(m));                }            };            return ret.toArray(new String[]{});        }    };    objectMapper = new ObjectMapper();    objectMapper.setAnnotationIntrospector(ignoreJsonTypeInfoIntrospector);


This solution worked for me. Check this for more info

 private static final JacksonAnnotationIntrospector IGNORE_ENUM_ALIAS_ANNOTATIONS = new JacksonAnnotationIntrospector() {    @Override    protected <A extends Annotation> A _findAnnotation(final Annotated annotated, final Class<A> annoClass) {        if (!annotated.hasAnnotation(JsonEnumAliasSerializer.class)) {            return super._findAnnotation(annotated, annoClass);        }        return null;    }};

And my custom annotation:

@Retention(RetentionPolicy.RUNTIME)@JacksonAnnotationsInside@JsonSerialize(using = JsonEnumSerializer.class)public @interface JsonEnumAliasSerializer {}

And ObjectMapper:

    final ObjectMapper objectMapper = new ObjectMapper();    objectMapper.setAnnotationIntrospector(IGNORE_ENUM_ALIAS_ANNOTATIONS);