来自序列化的基于自定义注释的忽略字段 [英] Custom annotation based ignore field from serialisation

查看:27
本文介绍了来自序列化的基于自定义注释的忽略字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个案例,我有2个Object Mapper实例. 我希望必须从序列化中排除使用某些自定义注释注释的字段 而其他映射器包括(忽略注释)

Consider a case that I have 2 instance of Object Mapper. I want one must exclude fields that are annotated with some custom annotation from serialization While other mapper includes(ignores annotation)

像类具有3个字段a,b,c,并且c带有一些注释(例如@IgnoreField) (他们将有n个班级,每个班级都有不打算序列化的字段)

Like class has 3 fields a,b,c and c is annotated with some annotation (say @IgnoreField) (Their will n number of class, each will have their Fields that are not meant to be serialized)

现在,第一个对象映射器o1必须仅序列化a和b. 第二个对象映射器o2可以序列化a,b和c.

Now 1st object mapper o1 must serialize only a and b. While 2nd object mapper o2 can serialize a,b and c.

对于任何具有不同字段的类,都可能会发生这种情况.

This can happen with any class having different fields some of which may be annotated.

推荐答案

您始终可以实现自定义JsonSerializer并将其注册到ObjectMapper.

You can always implement a custom JsonSerializer and register it with your ObjectMapper.

class Bean {
    @Ignore
    String a;
    String b;
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Ignore {

}

class BeanWithIgnoredFieldsSerializer extends JsonSerializer<Bean> {

    @Override
    public void serialize(final Bean value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeStartObject();
        try {
            for (final Field f : Bean.class.getFields()) {
                if (f.isAnnotationPresent(Ignore.class)) {
                    gen.writeStringField(f.getName(), (String) f.get(value));
                }
            }
        } catch (final Exception e) {
            //
        }
        gen.writeEndObject();
    }

}

class BeanModule extends SimpleModule {

    BeanModule() {
        addSerializer(Bean.class, new BeanWithIgnoredFieldsSerializer());
    }
}

void configure(final ObjectMapper om) {
    om.registerModule(new BeanModule());
}

请注意,我尚未测试此代码,但这是将自定义序列化程序添加到OM的一般思路.根据需要在serialize方法中调整代码.

Note I have not tested this code, but that is the general idea how you add custom serializers to the OM. Adjust the code within the serialize method however you want.

这篇关于来自序列化的基于自定义注释的忽略字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆