Jackson is one of the standard solutions in Java world when
you need to serialize/deserialize your classes. Not only it supports several different data formats, but
it’s also very well designed, documented and easy to use.
I’m particularly fond of mix-ins feature.
Mix-ins provide a convenient way to customize class (de)serialization without modifying it.
Let me first show you a simple example how you can serialize your class to YAML format
using Jackson.
Consider the following code:
Let’s suppose that we can’t or don’t want to modify MyClazz, but we want to skip b during serialization.
We can do it by adding a mix-in for this class:
Notice that we add @JsonIgnore annotation in mix-in class which duplicates MyClazz definitions.
You actually don’t need to duplicate all the definitions, we can use more Jackson magic instead, but I don’t
want to go into the details.
Imagine now that you need to add custom information to your serialized object. In our example let’s add c
property which equals a + b.
We can use JsonAppend
annotation for this purpose. It allows us to add “virtual” properties to our objects.
Let’s rewrite our example:
We don’t even have to modify ObjectMapper initialization! Our mix-in class still is the only
place containing all the information about MyClazz serialization.
To complete this story I’ll show an implementation of MyWriter. It’s just a class that knows
how to evaluate the value of our “virtual” property given an instance of MyClazz:
This happened after my 3d year at University (out of 5) in April 2013. Since the 4th year workload at Uni was
supposed to be decreasing, so I applied for an ...
Leave a comment