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 {
private final JsonSerializer
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) 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()));