How to override isEmpty method of JsonSerializer for specific class without overriding serialize method?

前端 未结 2 1319
一向
一向 2020-12-19 19:46

I want to add custom behaviour for isEmpty method.

When I extends from JsonSerializer

I should override

相关标签:
2条回答
  • 2020-12-19 20:24

    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()));
    
    0 讨论(0)
  • 2020-12-19 20:45

    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

    0 讨论(0)
提交回复
热议问题