如何在自定义序列化程序中访问默认 jackson 序列化 [英] How to access default jackson serialization in a custom serializer
问题描述
我想创建一个自定义序列化程序,它只做一点工作,然后将其余部分留给默认序列化.
I want to create a custom serializer which does a tiny bit of work and then leaves the rest for default serialization.
例如:
@JsonSerialize(using = MyClassSerializer.class)
public class MyClass {
...
}
public class MyClassSerializer extends JsonSerializer<MyClass> {
@Override
public void serialize(MyClass myClass, JsonGenerator generator,
SerializerProvider provider)
throws JsonGenerationException, IOException {
if (myClass.getSomeProperty() == someCalculationResult) {
provider.setAttribute("special", true);
}
generator.writeObject(myClass);
}
}
想为聚合对象创建其他自定义序列化程序,这些对象的行为基于特殊"属性值而有所不同.但是,上面的代码不起作用,因为它毫不奇怪地进入了无限递归.
With the idea of creating other custom serializers for aggregated objects which behave differently based on the 'special' attribute value. However, the above code does not work, as it unsurprisingly goes into an infinite recursion.
一旦我设置了属性,有没有办法告诉 jackson 使用默认序列化?我真的不想像许多自定义序列化程序一样枚举所有属性,因为该类相当复杂,而且我不想每次更改类时都必须对序列化程序进行双重维护.
Is there a way to tell jackson to use default serialization once I have set the attribute? I don't really want enumerate all the properties like many custom serializers as the class is fairly complex and I don't want to have to do dual maintenance with the serializer every time I change the class.
推荐答案
BeanSerializerModifier
将提供对默认序列化的访问.
A BeanSerializerModifier
will provide you access to the default serialization.
public class MyClassSerializer extends JsonSerializer<MyClass> {
private final JsonSerializer<Object> defaultSerializer;
public MyClassSerializer(JsonSerializer<Object> defaultSerializer) {
this.defaultSerializer = checkNotNull(defaultSerializer);
}
@Override
public void serialize(MyClass myclass, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (myclass.getSomeProperty() == true) {
provider.setAttribute("special", true);
}
defaultSerializer.serialize(myclass, gen, provider);
}
}
为 MyClass
创建一个 BeanSerializerModifier
public class MyClassSerializerModifier extends BeanSerializerModifier {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass() == MySpecificClass.class) {
return new MyClassSerializer((JsonSerializer<Object>) serializer);
}
return serializer;
}
}
注册序列化修饰符
ObjectMapper om = new ObjectMapper()
.registerModule(new SimpleModule()
.setSerializerModifier(new MyClassSerializerModifier()));
这篇关于如何在自定义序列化程序中访问默认 jackson 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!