3

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?

1
  • Can you provide more data, for list to json or the other way around? Commented Dec 26, 2019 at 17:35

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Lonash, Is there any way to use these on class level instead of each individual filed?
Yes, it is. But the logic in this case much more complex.
Dmitry, Would you like to give a hint how this can be done?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.