Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot, Jackson Convert empty string into NULL in Serialization

I have a requirement that while doing serialization I should be able to to convert all the properties that are with Empty string i.e "" to NULL, I am using Jackson in Spring boot, any idea how can I achieve this?

like image 625
Muhammad Avatar asked Dec 22 '25 03:12

Muhammad


1 Answers

Yep, it's very simple: use own Serializer for fields which can be empty and must be null:

class TestEntity {

    @JsonProperty(value = "test-field")
    @JsonSerialize(usung = ForceNullStringSerializer.class)
    private String testField;
}

class ForceNullStringSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null || value.equals("")) {
            gen.writeNull();
        } else {
            gen.writeString(value);
        }
    }
}

This serializer can be applied to all fields where you need to return null.

like image 148
Dmitry Ionash Avatar answered Dec 23 '25 16:12

Dmitry Ionash