Jackson 2.x tips: “Annotation Bundles”

aka How to use @JacksonAnnotationsInside

One of lesser known simple but sometimes super useful annotations Jackson provides is curiously named @JacksonAnnotationsInside .
What it does is quite simple: by adding this meta-annotation to another annotation, all other annotations contained will be introspected and added by Jackson, somewhat similar to how “mix-in” annotations are added from regular classes and interfaces.

Why would this be useful? Common use cases include:

  • Convenience: you can create one “combo-annotation” as short-hand to add multiple longer Jackson annotations
  • Encapsulation by 3rd party types: you can “hide” set of Jackson annotations within annotation type you define (and which may provide configuration other libraries too)

For example:

@JsonInclude(Include.NON_NULL) // only include non-null properties
@JsonPropertyOrder({ "id", "name" }) // ensure that 'id' and 'name'
// are always serialized before other properties
private @interface StdAnnotations { }

could be as convenient short-cut to establish default annotations, used like:

public class MyPOJO {
public String name;
public int id;
public List<Address> addresses;

Or, for simple Aliasing, you could create something like:

@Target({ElementType.METHOD, ElementType.FIELD}),
public @interface NonLoggable { }

to indicate that a POJO Field should not be logged, and when using Jackson for serialization it will achieve this using Jackson’s own @JsonIgnore annotation. For example, like:

public class MyMessage {
public int id;
public String name;
Context writeContext;

to make sure writeContext would not be included when instance was serialized, but without exposing the implementation detail of using Jackson under the hood (and need to expose Jackson annotation type(s)), or even just to use more meaningful name for convenience.

Written by

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store