Jackson Mixin — A simple guide to a powerful feature

shankar ganesh
2 min readJun 10, 2018

--

Jackson is the de-facto standard library for handling serialization and deserialization in the java world.
Using Jackson is as simple as decorating the class under inspection with the right annotations, and everything works out of the box.

However, consider the following use cases :-

  • The classes are part of a 3rd party library and cannot be modified
  • As a personal preference, you don’t want to add annotations to classes and want to handle it in a separate module

Introducing Jackson Mixin

In the following section, I’ll be adding the annotation ‘JsonProperty’, to a field which belongs to a class in a 3rd party library.
The approach can be applied for adding any annotation.

First, let’s look at the class in the 3rd party library.
For simplicity, let’s call it ‘Address’, which has a field ‘st’ which represents state :

class Address {
private String st;
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}

Consider the scenario, when you want to serialize the field ‘st’ as ‘state’.
Since we cannot add an annotation to the class, we will use the powerful mixin feature.

Let’s create an abstract class and call it StateMixin

public abstract class StateMixin {

@JsonProperty("state")
String st;
}

Now that we have created a mixin class, the next step involves linking the mixin with the object mapper.
The addMixInAnnotations method takes two arguments

  • The source model class
  • The mixin class
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Address.class, StateMixin.class);

Now the mapper instance can be used to serialize Address and the ‘st’ field will be serialized as ‘state’.

Address address = new Address();
address.setSt("California");
mapper.writeValueAsString(address);

And that’s all folks!

That was a simple guide to jackson mixins.

Please let me know if this was helpful.

--

--