I want to add custom behaviour for isEmpty method.
When I extends from JsonSerializer
I should override
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.
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;
}
}
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;
}
}
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()));
In the end you anyway have to have an implementation for the serialize method, as it is abstract. You couldn't instantiate your class if at least one method is left abstract