1

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

heycaptain
  • 45
  • 1
  • 7
  • Possible duplicate of [How to deserialize a blank JSON string value to null for java.lang.String?](https://stackoverflow.com/questions/30841981/how-to-deserialize-a-blank-json-string-value-to-null-for-java-lang-string) – Michał Krzywański Sep 26 '19 at 12:21
  • add this property in object mapper http://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_EMPTY_STRING_AS_NULL_OBJECT – Ryuzaki L Sep 26 '19 at 12:26
  • @Deadpool doesn't map empty Strings to null unfortunately – heycaptain Sep 26 '19 at 13:11
  • can you show your pojo class @heycaptain – Ryuzaki L Sep 26 '19 at 13:14
  • Possible duplicate of [Jackson: deserializing null Strings as empty Strings](https://stackoverflow.com/questions/20654810/jackson-deserializing-null-strings-as-empty-strings) – Durgpal Singh Sep 26 '19 at 13:23

1 Answers1

1

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);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • i added an if in the mapper, so the module would only be registered for specific POJOs, thank you @cassiomolin – heycaptain Sep 27 '19 at 09:04