简体   繁体   English

尝试使用 jackson 序列化 null Instant 时出错

[英]error trying to serialize null instant using jackson

I'm having some issues with jackson trying to serialize null instant objects.我在 jackson 尝试序列化空即时对象时遇到了一些问题。 In my db model i have some timestamps that are nullables and i want to be able to send them like that to the client.在我的数据库模型中,我有一些可以为空的时间戳,我希望能够像这样将它们发送给客户端。

The thing is that when i generate the response i see always these errors:问题是,当我生成响应时,我总是看到这些错误:

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:...

By debugging y show the field is an Instant.通过调试 y 显示该字段是 Instant。 This is the problematic getter...这是有问题的吸气剂...

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

I have tried to use the @JsonInclude annotation for the field, the getter and the whole class but I'm still getting that message and a 500 on the client.我试图对字段、getter 和整个类使用 @JsonInclude 注释,但我仍然在客户端收到该消息和 500。

I'm using Spring-boot which includes jackson 2.11.0.我正在使用包含 jackson 2.11.0 的 Spring-boot。

Thanks a lot非常感谢

You need to check variable startTime is not null first:您需要先检查变量startTime是否为null

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

Jackson invokes getter and checks whether value is null or not. Jackson调用 getter 并检查 value 是否为null But NullPointerException is thrown when getter is invoked.但是在调用getter时会抛出NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM