Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: how to prevent field serialization [duplicate]

Tags:

java

json

jackson

People also ask

How can we prevent field serialization?

writeValueAsString(currentUser); This will prevent password field to get serialized. Also you will be able to deserialize password fields as it is. Just make sure no filters are applied on the ObjectMapper object.

How can I skip optional empty field in Jackson serialization?

To exclude Optional. empty() fields, as the OP originally asked, one MUST add the depencandy and MUST set NON_ABSENT. NON_NULL is not enough.

Does Jackson serialize null fields?

With its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.

How do I ignore properties in ObjectMapper?

ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.


You can mark it as @JsonIgnore.

With 1.9, you can add @JsonIgnore for getter, @JsonProperty for setter, to make it deserialize but not serialize.


Illustrating what StaxMan has stated, this works for me

private String password;

@JsonIgnore
public String getPassword() {
    return password;
}

@JsonProperty
public void setPassword(String password) {
    this.password = password;
}

The easy way is to annotate your getters and setters.

Here is the original example modified to exclude the plain text password, but then annotate a new method that just returns the password field as encrypted text.

class User {

    private String password;

    public void setPassword(String password) {
        this.password = password;
    }

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    @JsonProperty("password")
    public String getEncryptedPassword() {
        // encryption logic
    }
}

Starting with Jackson 2.6, a property can be marked as read- or write-only. It's simpler than hacking the annotations on both accessors and keeps all the information in one place:

public class User {
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
}