Oops Null Pointer

Java programming related

Jackson Custom Deserializer Example – Annotated MixIn

Having  just recently started using Jackson I ran into the issue of a serialising a old-style static enum pattern class. This class has no constructor (all “enum” options are static instances) so I had to make my own deserialiser.

There are two ways to map the custom deserialiser – via a Mixin or via a factory.

Mix in:

Create a MixIn for the Class that contains the Enum – overriding the field or setter


public abstract class JacksonMyStaticEnumMixIn {

  JacksonMyStaticEnumMixIn() { }

  @JsonDeserialize(using=MyStaticEnumDeserializer.class)
  public MyStaticEnum myStaticEnum;
}

Then add this to the object mapper:

ObjectMapper mapper = new ObjectMapper();
// Implicit deserialisation mapping via mix in class
mapper.getDeserializationConfig().addMixInAnnotations( ClassContainingStaticEnum.class, JacksonMyStaticEnumMixIn.class);

Explicit Binding:

The mix-in method can not be checked by the compiler and requires discovery, rather than being intuitive. The other option is an explicit binding via a factory as follows:

ObjectMapper mapper = new ObjectMapper();
CustomDeserializerFactory factory = new CustomDeserializerFactory();
factory.addSpecificMapping(MyStaticEnum.class, new MyStaticEnumDeserializer());
mapper.setDeserializerProvider(new StdDeserializerProvider(factory));
Advertisements

2 responses to “Jackson Custom Deserializer Example – Annotated MixIn

  1. Cristian Vrabie December 30, 2010 at 10:31 pm

    Thanks! That saved me some searching.
    Can I ask what class did you extend to do the MyStaticEnumDeserializer? Was it org.codehaus.jackson.map.deser.BeanDeserializer?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: