Reputation: 55
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
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