简体   繁体   中英

Jackson - Transform field value on serialization

In a Spring Boot applicaion with AngularJS frontend, a "Pin" field value has to be blackened on serialization, ie, 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?

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.

Try the following example.

public class Card {
    public int id;
    public String pin;
}

public class CardSerializer extends StdSerializer<Card> {

    public CardSerializer() {
        this(null);
    }

    public CardSerializer(Class<Card> t) {
        super(t);
    }

    @Override
    public void serialize(Card value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeStringField("pin", "****");
        jgen.writeEndObject();
    }
}

Then you need to register your customer serializer with the ObjectMapper

Card card = new Card(1, "12345");
ObjectMapper mapper = new ObjectMapper();
 
SimpleModule module = new SimpleModule();
module.addSerializer(Card.class, new CardSerializer());
mapper.registerModule(module);
String serialized = mapper.writeValueAsString(card);

There are some improvements you can do here like registering the serializer directly on the class, but you can read more about it here Section 4 - http://www.baeldung.com/jackson-custom-serialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM