【问题标题】:ObjectMapper throws JsonMappingException when it try to construct instance with null fieldObjectMapper 在尝试使用空字段构造实例时抛出 JsonMappingException
【发布时间】:2019-10-31 18:28:11
【问题描述】:

我尝试将对象序列化为 json 字符串,什么会有空字段。 当所有字段初始化时 - 一切正常,但是当我设置字段 null 值时,我得到了异常:

com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException).

我的代码:

public String toJsonString(T t) throws JsonProcessingException{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    String dtoAsString = objectMapper.writeValueAsString(t); //string where I got the exception
    return dtoAsString;
}

对象:

SomeObject{
    @JsonSerialize(using = LocalDateSerializer.class)
    LocalDate date = LocalDate.now();
    Long value = null;
}

PS:

问题在于我无法在 json 中自动解析 someObject,因为我遇到了另一个异常 - 我需要将 date 解析为特殊的字符串格式。所以我需要完全按照我的方式使用 - objectMapper(Gson().toString 错误地序列化了我的 LocalDate 值)。

【问题讨论】:

    标签: java json serialization objectmapper


    【解决方案1】:

    我找到了解决办法:

    由于其中一个字段尚未初始化而发生错误,因此ObjectMapper 引发了异常。

    只需将@JsonInclude(JsonInclude.Include.NON_NULL) 添加到您的 POJO 类中:

    @JsonInclude(JsonInclude.Include.NON_NULL)
    
    SomeObject{
        String date = "11.01.19";
        Long value = null;
    }
    

    结果我们将得到没有可为空字段的json:

    {
        "date" : "11.09.19"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多