Search code examples
javaspringspring-bootjackson2

How to ignore a NULL value during Deserialization in lamda stream?


I have getter method

@JsonInclude(Include.NON_NULL)
public Date getVerifiedFrom() {
    if(invoices == null || invoices.isEmpty()) {
       return null;
    }
    return invoices.stream().filter(i->i.getVerifiedDate() != null).map(Invoice::getVerifiedDate).min(Date::compareTo).get();
}

I have tried few link but those are not helped,

http://www.java2novice.com/java-json/jackson/ignore-json-null-elements/

How to deserialize Jackson Json NULL String to Date with JsonFormat

http://www.davismol.net/2016/01/08/jackson-how-to-exclude-null-value-properties-from-json-serialization/

How to tell Jackson to ignore a field during serialization if its value is null?

Error:

Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No value present; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: No value present (through reference chain: java.util.ArrayList[0]->com.enkindle.service.resource.TradeDebtResource["verifiedFrom"])

Solution

  • The exception you’re getting is due to the stream being empty, which causes min to return an empty optional which throws an exception when you call get. The reason you don’t get the original NPE is that Jackson probably extracts just the message.

    You should replace get() with orElse(null). There’s also a Jackson module that handles Optional.