Home > Java > javaTutorial > How to Leverage Jackson's Default Deserializer within a Custom Deserializer?

How to Leverage Jackson's Default Deserializer within a Custom Deserializer?

Patricia Arquette
Release: 2024-12-10 09:16:12
Original
908 people have browsed it

How to Leverage Jackson's Default Deserializer within a Custom Deserializer?

How to Call Default Deserializer from a Custom Deserializer in Jackson

When customizing deserialization in Jackson, you may encounter the need to access the default deserializer to populate your object. This can be achieved by employing a BeanDeserializerModifier and registering it via a SimpleModule.

Here's an example implementation:

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

  @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);
  }
}
Copy after login

By registering this modifier, you can access the default deserializer and pre-populate your object within your custom deserializer without causing an exception.

The above is the detailed content of How to Leverage Jackson's Default Deserializer within a Custom Deserializer?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template