Jackson 2.12 Most Wanted (2/5):
@JsonIncludeProperties
(part 2 of “Deeper Dive on Jackson 2.12” mini-series — see “Jackson 2.12 Features” for context)
Another rather old Jackson Feature Request — jackson-databind#1296 from summer of 2016 — was also included in Jackson 2.12.0 release.
This feature request was asking for something similar to existing @JsonIgnoreProperties
annotation which works like so:
@JsonIgnoreProperties({ "password" })
public class Stuff {
public int id;
public String name;
public String password;
}// serialized as:
{ "id" : 124, "name" : "thingy" }
in this case serialization of value of property password
would be prevented and only id
and name
properties would be included.
But while this works for many cases it may be an unwieldy — and more importantly, potentially unsafe — way to indicate inclusion criteria.
There are also per-property annotations like @JsonProperty
to include and @JsonIgnore
to exclude properties, wouldn’t it be more convenient to have just one annotation to define everything that should be included but leave out everything else?
This is exactly what @JsonIncludeProperties
does. Example above could be translated into:
@JsonIncludeProperties({ "id", "name" })
public class Stuff {
public int id;
public String name;
public String password;
}// serialized as:
{ "id" : 124, "name" : "thingy" }
Simple.
Caveats
Note that for inclusion to work, properties need to be “visible” — that is, their access level needs to be such that they are auto-discovered (for fields and getter methods this means public
, for setters any access level is acceptable).
If you want looser restrictions you can use @JsonAutoDetect
to make “everything visible”, f.ex:
@JsonAutoDetect(fieldVisibility=Visibility.ANY)
@JsonIncludeProperties({ "x", "y" })
public class Coordinates {
private int x, y;
private String secret;
}
(or set per-mapper visibility defaults similarly)
Use cases
The main use case, based on user comments, is to ensure accidental inclusion of new properties: when class annotation specifies inclusion set, an addition of a field or a getter or setter method will not by itself lead to changes in serialization.