Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Transform field value on serialization

In a Spring Boot applicaion with AngularJS frontend, a "Pin" field value has to be blackened on serialization, i.e., if the Pin field value is null in the POJO, the according JSON field has to remain blank; if the field value contains data, it has to be replaced with a "***" string.

Does Jackson provide a feature to get this done?

like image 699
Mr.Radar Avatar asked Sep 01 '25 01:09

Mr.Radar


1 Answers

You can do it easily like following without any Custom Serializer

public class Pojo {
    @JsonIgnore
    private String pin;

    @JsonProperty("pin")
    public String getPin() {
        if(pin == null) {
            return "";
        } else {
            return "***";
        }
    }

    @JsonProperty("pin")
    public void setPin(String pin) {
        this.pin = pin;
    }

    @JsonIgnore
    public String getPinValue() {
        return pin;
    }

}

You can use Pojo.getPinValue() to get the exact value.

like image 136
shazin Avatar answered Sep 02 '25 14:09

shazin