Acampoh
Acampoh

Reputation: 669

error trying to serialize null instant using jackson

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

Upvotes: 0

Views: 920

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38625

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.

Upvotes: 2

Related Questions