heycaptain
heycaptain

Reputation: 55

Jackson Deserialization of all empty Strings to null in class

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

Upvotes: 2

Views: 4048

Answers (1)

cassiomolin
cassiomolin

Reputation: 130857

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);

Upvotes: 3

Related Questions