Custom Deserialization with Default Behavior in Jackson
When implementing custom deserializer in Jackson, it may be necessary to utilize the default deserializer to pre-populate an object before applying custom logic. This article addresses the challenge of accessing the default deserializer from a custom one.
To achieve this, create a BeanDeserializerModifier and register it using a SimpleModule. Here's an example:
public class UserEventDeserializer extends StdDeserializer<User> implements ResolvableDeserializer { private static final long serialVersionUID = 7923585097068641765L; private final JsonDeserializer<?> defaultDeserializer; public UserEventDeserializer(JsonDeserializer<?> defaultDeserializer) { super(User.class); this.defaultDeserializer = defaultDeserializer; } @Override public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { User deserializedUser = (User) defaultDeserializer.deserialize(jp, ctxt); // Special logic return deserializedUser; } @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (beanDesc.getBeanClass() == User.class) return new UserEventDeserializer(deserializer); return deserializer; } }); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); User user = mapper.readValue(new File("test.json"), User.class); } }
In this example:
By registering this module with an ObjectMapper, the custom deserialization logic can be used while still benefiting from the default behavior for other classes.
The above is the detailed content of How Can I Leverage Default Deserialization Behavior Within a Custom Jackson Deserializer?. For more information, please follow other related articles on the PHP Chinese website!