How to control Jackson serialization of a library class
You can use a mixin to make sure that the class is serialized as per your needs. Consider the following:
// The source class (where you do not own the source code)
public class ColorRGBA {
public float a; // <-- Want to skip this one
public float b;
public float g;
public float r;
}
Then, create the mixin where you ignore the a
property.
// Create a mixin where you ignore the "a" property
@JsonIgnoreProperties("a")
public abstract class RGBMixin {
// Other settings if required such as @JsonProperty on abstract methods.
}
Lastly, configure your mapper with the mixin:
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(ColorRGBA.class, RGBMixin.class);
System.out.println(mapper.writeValueAsString(new ColorRGBA()));
The output will be:
{"b":0.0,"g":0.0,"r":0.0}
Note that the method ObjectMapper.addMixInAnnotations
is deprecated from Jackson 2.5 and should be replaced with the more fluent version:
mapper.addMixIn(ColorRGBA.class, RGBMixin.class);
The JavaDocs can be found here