考虑我有 2 个对象映射器实例的情况。
我希望必须从序列化中排除使用某些自定义注释进行注释的字段
而其他映射器包括(忽略注释)
就像类有 3 个字段 a、b、c 一样,c 也用一些注释进行注释(例如 @IgnoreField)
(他们将有 n 个类,每个类都有其不打算序列化的字段)
现在第一个对象映射器 o1 必须仅序列化 a 和 b。
而第二个对象映射器 o2 可以序列化 a、b 和 c。
对于具有不同字段(其中一些字段可能带有注释)的任何类都可能发生这种情况。
您始终可以实施自定义JsonSerializer
并将其注册到您的 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
你想要的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)