How do I call the default deserializer from a custom deserializer in Jackson

前端 未结 11 1012
野趣味
野趣味 2020-11-22 14:26

I have a problem in my custom deserializer in Jackson. I want to access the default serializer to populate the object I am deserializing into. After the population I will do

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:49

    You are bound to fail if you try to create your custom deserializer from scratch.

    Instead, you need to get hold of the (fully configured) default deserializer instance through a custom BeanDeserializerModifier, and then pass this instance to your custom deserializer class:

    public ObjectMapper getMapperWithCustomDeserializer() {
        ObjectMapper objectMapper = new ObjectMapper();
    
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer modifyDeserializer(DeserializationConfig config,
                        BeanDescription beanDesc, JsonDeserializer defaultDeserializer) 
                if (beanDesc.getBeanClass() == User.class) {
                    return new UserEventDeserializer(defaultDeserializer);
                } else {
                    return defaultDeserializer;
                }
            }
        });
        objectMapper.registerModule(module);
    
        return objectMapper;
    }
    

    Note: This module registration replaces the @JsonDeserialize annotation, i.e. the User class or User fields should no longer be annotated with this annotation.

    The custom deserializer should then be based on a DelegatingDeserializer so that all methods delegate, unless you provide an explicit implementation:

    public class UserEventDeserializer extends DelegatingDeserializer {
    
        public UserEventDeserializer(JsonDeserializer delegate) {
            super(delegate);
        }
    
        @Override
        protected JsonDeserializer newDelegatingInstance(JsonDeserializer newDelegate) {
            return new UserEventDeserializer(newDelegate);
        }
    
        @Override
        public User deserialize(JsonParser p, DeserializationContext ctxt)
                throws IOException {
            User result = (User) super.deserialize(p, ctxt);
    
            // add special logic here
    
            return result;
        }
    }
    

提交回复
热议问题