简体   繁体   中英

ObjectMapper avoid annotation

I have annotations like this:

    @Valid
@NotNull
@JsonTypeResolver(com.rsqtechnologies.sioms.shared.JsonTypeResolver.class)
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type",
        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = HandballPlayerTO.class, name = "handballPlayerTO"),
        @JsonSubTypes.Type(value = FootballPlayerTO.class, name = "footballPlayerTO")
})

And wanna to avoid @JsonTypeResolver during using objectMapper.

I've tried this:

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

But as I noticed it removes all annotations that appears next to.

The _findTypeResolver method handles @JsonTypeResolver, @JsonTypeInfo and @JsonTypeIdResolver. By overriding this method, you prevent Jackson from processing all of them. Instead of overriding _findTypeResolver, override _findAnnotation so that Jackson can still see the others.

JacksonAnnotationIntrospector ignoreJsonTypeInfoIntrospector = new JacksonAnnotationIntrospector() {
    protected <A extends Annotation> A _findAnnotation(Annotated annotated, Class<A> annoClass) {
        return JsonTypeResolver.class == annoClass ? null : annotated.getAnnotation(annoClass);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM