英文:
error trying to serialize null instant using jackson
问题
我在使用 Jackson 序列化空的 Instant 对象时遇到了一些问题。在我的数据库模型中,我有一些可以为空的时间戳,我希望能够将它们原样发送给客户端。
问题在于当我生成响应时,我总是看到以下错误:
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: 无法编写 JSON: (was java.lang.NullPointerException); 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain:...
通过调试,我发现该字段是一个 Instant。这是有问题的 getter 方法...
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Instant getStartTime() {
return startTime.toInstant();
}
我尝试过为字段、getter 方法和整个类使用 @JsonInclude 注解,但我仍然收到该消息,并在客户端上收到 500 错误。
我正在使用 Spring Boot,其中包含 jackson 2.11.0。
非常感谢。
英文:
I'm having some issues with jackson trying to serialize null instant objects. 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. 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.
I'm using Spring-boot which includes jackson 2.11.0.
Thanks a lot
答案1
得分: 2
你需要首先检查变量 startTime
是否为 null
:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Instant getStartTime() {
return startTime != null ? startTime.toInstant() : null;
}
Jackson
调用 getter 并检查值是否为 null
。但是在调用 getter 时会抛出 NullPointerException
。
英文:
You need to check variable startTime
is not null
first:
@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. But NullPointerException
is thrown when getter
is invoked.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论