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;
}
This more of a Jackson question than a Spring question. You would just need to register your custom deserializer with the ObjectMapper...
How you get access to that ObjectMapper depends on if you are using Spring Boot or just plain Spring.