如何在自定义序列化程序中访问默认的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);
}
}
创建其他自定义序列化程序以进行聚合基于'speical'属性值表现不同的对象。但是,上面的代码不起作用,因为毫无疑问会进入无限递归。
With the idea that of creating other custom serializers for aggregated objects which behave differently based on the 'speical' 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);
}
}
创建 BeanSerializerModifier
for MyClass
Create a BeanSerializerModifier
for MyClass
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;
}
}
注册序列化修饰符
Register the serializer modifier
ObjectMapper om = new ObjectMapper()
.registerModule(new SimpleModule()
.setSerializerModifier(new MyClassSerializerModifier()));
这篇关于如何在自定义序列化程序中访问默认的jackson序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!