I have a user object that is sent to and from the server. When I send out the user object, I don't want to send the hashed password to the client. So, I added @JsonIgnore
on the password property, but this also blocks it from being deserialized into the password that makes it hard to sign up users when they don't have a password.
How can I only get @JsonIgnore
to apply to serialization and not deserialization? I'm using Spring JSONView, so I don't have a ton of control over the ObjectMapper
.
Things I've tried:
@JsonIgnore
to the property@JsonIgnore
on the getter method onlyIf there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
To ignore any unknown properties in JSON input without exception, we can set ignoreUnknown=true of @JsonIgnoreProperties annotation.
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore
to the getter.
Which you've tried:
Add @JsonIgnore on the getter method only
Do this, and also add a specific @JsonProperty
annotation for your JSON "password" field name to the setter method for the password on your object.
More recent versions of Jackson have added READ_ONLY
and WRITE_ONLY
annotation arguments for JsonProperty
. So you could also do something like:
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private String password;
Docs can be found here.
In order to accomplish this, all that we need is two annotations:
@JsonIgnore
@JsonProperty
Use @JsonIgnore
on the class member and its getter, and @JsonProperty
on its setter. A sample illustration would help to do this:
class User { // More fields here @JsonIgnore private String password; @JsonIgnore public String getPassword() { return password; } @JsonProperty public void setPassword(final String password) { this.password = password; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With