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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.