Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write-only properties with Jackson

Tags:

java

json

jackson

In my entity class, I'm trying to make a write-only field (gets ignored during serialization, but gets de-serialized normally).

@JsonProperty
@JsonSerialize(using=NullSerializer.class)
public String getPassword() {
    return password;
}

This almost gives me what I want: the JSON contains the "password" field, but the value is always null. How do I remove the field entirely?

like image 337
Mike Baranczak Avatar asked Aug 08 '12 20:08

Mike Baranczak


People also ask

Does Jackson use getter or field?

Jackson uses the setter and getter methods to auto-detect the private field and updates the field during deserialization. Assume you have defined all the fields or properties in your Java class so that both input JSON and output Java class have identical fields.

Does Jackson use getters and setters?

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

How do I ignore JSON property?

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.


2 Answers

Use @JsonIgnore on just the getter getPassword, instead of using the NullSerializer. Then also use @JsonProperty("password") on the setter.

This should allow password to be de-serialized, but the JSON output of serialization won't include it.

For example, a "getter" method that would otherwise denote a property (like, say, "getValue" to suggest property "value") to serialize, would be ignored and no such property would be output unless another annotation defines alternative method to use.

like image 104
pb2q Avatar answered Oct 22 '22 19:10

pb2q


You can set access value:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
like image 41
radeklos Avatar answered Oct 22 '22 20:10

radeklos