How to configure JSON deserialization in Spring to set null values if JSON property is empty string?

2.2k views Asked by At

I created custom JsonDeserializer for that can be applied to any field with type String.

public class EmptyToNullStringDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = jp.getText();
        return "" == text ? null : text;
    }
}

It can be used in models.

class SomeClass {
    @JsonDeserialize(using = EmptyToNullStringDeserializer.class)
    private String someField;
}

It converts JSON

{"someField": ""}

into Java object where someField equals to null (not "")

Question: How to create generic JsonDeserializer that sets null to all Java object fields that equals to "" in JSON? It should be used as:

@JsonDeserialize(using = EmptyToNullStringDeserializer.class)
class SomeClass {
        private String someField;
}
2

There are 2 answers

0
hyness On

This more of a Jackson question than a Spring question. You would just need to register your custom deserializer with the ObjectMapper...

SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addDeserializer(String.class, new EmptyToNullStringDeserializer());
mapper.registerModule(module);

How you get access to that ObjectMapper depends on if you are using Spring Boot or just plain Spring.

0
Srinivasa R On

You need to register your custom deserializer with ObjectMapper