[英]Jackson Deserialization of all empty Strings to null in class
I have multiple POJOs, for some of them I would like to deserialize all empty Strings to null
.我有多个 POJO,其中一些我想将所有空字符串反序列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?有没有办法(可能是注释?)让我告诉 Jackson 哪些 POJO 应该将所有空字符串反序列化为null
,哪些不应该?
Not a duplicate, i'm looking for a solution which works on a class, not individual fields不是重复的,我正在寻找适用于 class 的解决方案,而不是单个字段
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
:将其添加到Module
,然后将Module
注册到您的ObjectMapper
:
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new EmptyStringAsNullDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.