Problem:
Creating a custom deserializer in Jackson that allows access to the default deserializer for pre-populating objects before applying custom logic.
Code:
public class UserEventDeserializer extends StdDeserializer<User> { public UserEventDeserializer() { super(User.class); } @Override public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // Line causing UnsupportedOperationException: User deserializedUser = super.deserialize(jp, ctxt, new User()); } }
Solution:
Implement a BeanDeserializerModifier to register a custom deserializer for a specific class.
Code:
public class UserEventDeserializer extends StdDeserializer<User> implements ResolvableDeserializer { 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; } // Required when modifying BeanDeserializer @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } public static void main(String[] args) throws Exception { 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); } }
The above is the detailed content of How to Call Jackson's Default Deserializer from a Custom Deserializer?. For more information, please follow other related articles on the PHP Chinese website!