【问题标题】:Jackson Deserialization of all empty Strings to null in class杰克逊在课堂上将所有空字符串反序列化为空
【发布时间】:2019-09-26 21:27:50
【问题描述】:

我有多个 POJO,其中一些我想要 将所有空字符串反序列化为null

对我来说有没有办法(可能是注释?) 告诉杰克逊哪些 POJO 应该反序列化 null 的所有空字符串, 哪些不应该?

不是重复的,我正在寻找一种适用于类而不是单个字段的解决方案

【问题讨论】:

标签: java jackson


【解决方案1】:

定义一个序列化器如下:

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;
        }
    }
}

将其添加到Module,然后将Module 注册到您的ObjectMapper

SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new EmptyStringAsNullDeserializer());

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

【讨论】:

  • 我在映射器中添加了一个 if,因此该模块只会为特定的 POJO 注册,谢谢@cassiomolin
猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多