禁用Jackson映射器以获取特定注释

时间:2012-12-27 15:03:43

标签: java json annotations jackson

使用Jackson,可以轻松禁用给定ObjectMapper的所有注释。 有没有办法只禁用一个给定的注释?

// disable all
ObjectMapper mapper = new ObjectMapper()
mapper.disable(MapperFeature.USE_ANNOTATIONS);

// disable one?
ObjectMapper mapper = new ObjectMapper()
mapper.disable(@JsonIgnore);

使用@JacksonAnnotationsInside,我定义了一个自定义杰克逊注释,我只希望它在某些情况下使用。

3 个答案:

答案 0 :(得分:1)

这是我遇到的最好的。我想我是在某个地方的Jackson用户组论坛上看到的。

本质上,它创建了一个自定义注释introspector,如果它看到它有一个特定的注释(在本例中为JsonTypeInfo),则返回null

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);

答案 1 :(得分:0)

我认为最好覆盖findPropertiesToIgnore这样的方法:

    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);

答案 2 :(得分:0)

这个解决方案对我有用。查看this了解详情

 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;
    }
};

我的自定义注释:

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

和ObjectMapper:

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