Jackson: how to prevent field serialization
To omit a field from serialization in Jackson, slap a @JsonIgnore
on it. For a blanket, class-wide approach, wrap it up in @JsonIgnoreProperties
and specify the fields to leave out.
Example with @JsonIgnore
:
Managing multiple fields or want external configuration? Use a mixin with @JsonIgnoreProperties
:
Special cases: Locking away the crown jewels
When you're dealing with the Coca-Cola formula (aka sensitive information, like a password), security and functionality need to walk hand-in-hand. Jackson annotations are your bouncers here; they'll let the right folks in and keep the riff-raff out.
@JsonIgnore and @JsonProperty: Sherlock and Watson
To accept but not divulge a field (like when a client updates a password), apply @JsonIgnore
to the getter and @JsonProperty
to the setter (like Sherlock hiding clues and Watson revealing solutions):
JsonProperty.Access.WRITE_ONLY: The VIP area
Jackson 2.6 gave us JsonProperty.Access.WRITE_ONLY
, a velvet rope that lets VIPs (properties) out of the club (JSON output), but only bouncers (read operations) are allowed back in:
Advanced tricks: More than just card tricks
Encrypted fields: The Enigma machine
To store an encrypted version of a field, @JsonProperty
comes to the rescue on a custom getter:
JSON Views: Now you see me
To conditionally expose fields, initiate JSON Views protocol:
@JsonIgnoreProperties
: The crystal ball
Using @JsonIgnoreProperties
is like having a crystal ball for serialization and deserialization:
Was this article helpful?