In order to modify the isEmpty
behavior but maintain default serialization you can take advantage of a serializer modifier. You still have to implement a custom serializer, but you can utilize default serialization pretty cleanly.
Create a custom serializer with the default serializer injected
Inject a defaultSerializer
variable in to your custom serializer class. You will see where this serializer comes from when we implement the modifier. In this class you will override the isEmpty
method to accomplish what you need. Below, if MySpecificClass
has a null id
it is considered empty by Jackson.
public class MySpecificClassSerializer extends JsonSerializer<MySpecificClass> {
private final JsonSerializer<Object> defaultSerializer;
public MySpecificClassSerializer(JsonSerializer<Object> defaultSerializer) {
this.defaultSerializer = checkNotNull(defaultSerializer);
}
@Override
public void serialize(MySpecificClass value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
defaultSerializer.serialize(value, gen, serializers);
}
@Override
public boolean isEmpty(SerializerProvider provider, MySpecificClass value) {
return value.id == null;
}
}
Create a custom BeanSerializerModifier
Extend BeanSerializerModifier
and override the modifySerializer
method. Inside of this method you can filter on the class type that you want to operate on, and return your custom serializer accordingly.
public class MyClassSerializerModifier extends BeanSerializerModifier {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass() == MySpecificClass.class) {
return new MySpecificClassSerializer((JsonSerializer<Object>) serializer);
}
return serializer;
}
}
Register the modifier with the ObjectMapper
Registering the modifier will allow your serializer to trigger anytime the condition in modifySerializer
is met.
ObjectMapper om = new ObjectMapper()
.registerModule(new SimpleModule()
.setSerializerModifier(new MyClassSerializerModifier()));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…