【问题标题】:error trying to serialize null instant using jackson尝试使用杰克逊序列化空瞬间时出错
【发布时间】:2021-01-03 14:53:15
【问题描述】:

杰克逊尝试序列化空即时对象时遇到了一些问题。在我的数据库模型中,我有一些可以为空的时间戳,我希望能够像这样将它们发送给客户端。

问题是,当我生成响应时,我总是看到这些错误:

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain:...

通过调试 y 显示该字段是 Instant。这是有问题的吸气剂...

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    public Instant getStartTime() {
        return startTime.toInstant();
    }

我尝试对字段、getter 和整个类使用 @JsonInclude 注释,但我仍然收到该消息和客户端上的 500。

我正在使用包含 jackson 2.11.0 的 Spring-boot。

非常感谢

【问题讨论】:

    标签: java json spring-boot serialization jackson


    【解决方案1】:

    您需要先检查变量startTime 不是null

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    public Instant getStartTime() {
        return startTime != null ? startTime.toInstant() : null;
    }
    

    Jackson 调用 getter 并检查 value 是否为 null。但是在调用getter 时会抛出NullPointerException

    【讨论】:

    • 我需要多睡觉 :facepalm: 非常感谢!
    • @Acampoh,没问题。有时我们只见树木不见森林。评论SO 支持 unicode 符号:?。 ?
    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多