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
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;
}
}