I have a custom serializer to treat String with blank values as null and also to trim trailing blank spaces. Follwoing is the code for the same. -
public class StringSerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String finalValue = null;
if (value != null) {
finalValue = value.trim();
if (finalValue.isEmpty()) {
finalValue = null;
}
}
gen.writeObject(finalValue);
}
}
In the main bean definition, the attribute definition is as follows -
public class SampleBean {
private Long id;
@JsonSerialize(using = StringSerializer.class)
@JsonInclude(Include.NON_NULL)
private String attribute1;
@JsonSerialize(using = StringSerializer.class)
@JsonInclude(Include.NON_NULL)
private String attribute2;
//Getters and setters
}
In the cases where the custom serializer kicks in, the not null values aren't ignored.
For example:
SampleBean bean = new SampleBean();
bean.setId(1L);
bean.setAttribtute1("abc");
bean.setAttribtute2(" ");
new ObjectMapper().writeValueAsString(bean);
The output of writeValueAsString: {"id": 1, "attribute1": "abc", "attribute2": null}
Expected output since i have @JsonInclude(Include.NON_NULL) in attribute 2, is as below. {"id": 1, "attribute1": "abc"}
Is there anyway to achieve this?