2

I have multiple POJOs, for some of them I would like to deserialize all empty Strings to null.

Is there a way (annotation maybe?) for me to tell Jackson which POJOs should deserialize all empty Strings to null, and which shouldn't?

Not a duplicate, i'm looking for a solution which works on a class, not individual fields

5

1 Answer 1

3

Define a serializer as follows:

public class EmptyStringAsNullDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, 
                              DeserializationContext deserializationContext) 
                              throws IOException {

        String value = jsonParser.getText();
        if (value == null || value.isEmpty()) {
            return null;
        } else {
            return value;
        }
    }
}

Add it to a Module and then register the Module to your ObjectMapper:

SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new EmptyStringAsNullDeserializer());

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Sign up to request clarification or add additional context in comments.

1 Comment

i added an if in the mapper, so the module would only be registered for specific POJOs, thank you @cassiomolin

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.