Jackson 2.x tips: “Annotation Bundles”

@cowtowncoder
2 min readOct 3, 2019

--

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:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE}),
@JacksonAnnotationsInside
@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:

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

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD}),
@JacksonAnnotationsInside
@JsonIgnore
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;
@NonLoggable
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.

--

--

@cowtowncoder
@cowtowncoder

Written by @cowtowncoder

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

No responses yet