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