Explain Codes LogoExplain Codes Logo

Only using @JsonIgnore during serialization, but not deserialization

java
serialization
deserialization
jackson-annotations
Alex KataevbyAlex Kataev·Oct 27, 2024
TLDR

Jackson has your back when you need to serialize but not deserialize a field in Java. Apply @JsonProperty(access = Access.WRITE_ONLY). Effectively, this makes the field eligible for writing on deserialization but hides it from reading during serialization.

public class User { @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private String password; //Also known as "write-only memory" :D // getters & setters }

That's how you place a cone of silence over the password field when a User object gets translated into JSON, yet you can hear it loud and clear when the JSON data revives back to a User object.

Additional considerations

Version compatibility

The Access.WRITE_ONLY and Access.READ_ONLY directives are strictly for Jackson library Version 2.6 and beyond. Older versions will give you the proverbial cold shoulder.

Field-level caution

A field-level @JsonIgnore looks tempting, but beware! It will put the password under a cloak of invisibility for both serialization and deserialization. Instead, send @JsonIgnore the getter's way and keep it contained to serialization alone.

The old-school way

Old is gold! That's why in Jackson version 1.9, decorators used to put @JsonIgnore on a getter method. Complementing it with @JsonProperty on the setter was a popular dance move to keep deserialization in the game.

Handling complex situations

Mixed behaviors

When dealing with networks of objects, a class level @JsonIgnoreProperties(value = {"sensitiveData"}, allowSetters = true) lets Jackson know about fields that put up a wall for serialization, yet roll out the red carpet for deserialization.

Customizing for control

Create custom serializers and deserializers when you feel a deep-seated need to control how serialization logic behaves at a more intimate level than what annotations alone can provide.

Compatibility check

Be vigilant! Ensure your Jackson version is playing nice with the custom adaptors you use. Peace in the adapter kingdom is key for smooth runtime behavior.

Brandishing Extra Caution

Beware of package clones

Import the right package for Jackson annotations. Trust me, it's a jungle out there with similar sounding classes lurking in different jackson-databind or jackson-annotations packages.

Test everything

Unit testing both serialization and deserialization loops will save you from nasty surprises. Picture this, a rogue password field leaking into serialized payload in your signup API. Yikes!