Search code examples
javadatejacksonnullresponse

Send date field as empty in response instead of setting to null and not sending in response


I am currently dealing with a scenario where in the DB I have a date column that has NULL values set. When I test the below code and get my response, the field is not even coming in my response when that value is NULL. How can I automatically send the field in the response and handle the NULL scenario, sending a blank value such as an empty string? The field is required to send in the response (userIndDate which is a java.util.Date object). I am using jackson to serialize the data. I have not include my repo which is doing the db->object mapping just to condense the code. Below is the code snippet?

var newResponse =  SearchResponse.builder()
            .item((Integer) row[0]).itemDesc((String) row[1])
            .loc(String.valueOf((Integer ) row[2])).locDesc((String) row[3])
            .ase((BigDecimal) (row[4]))
            .aseStartDate((row[5] != null ? (java.util.Date)(row[5]) : null))
            .indDate(row[6] != null ? (java.util.Date)(row[6]) : null)
            .userIndDate((row[7] != null ? (java.util.Date)(row[7]) : null))
            .seasonalProfileName((String) (row[8]))
            .build();

        resultStream.add(newResponse);
        return newResponse;

Response is below when the userIndDate column is NULL at db end (i.e. missing in the response):

{
    "searchResponse": [
        {
            "loc": "1",
            "item": 2,
            "itemDesc": "someItemDesc",
            "locDesc": "someLocDesc",
            "ase": 1.00000000000000000,
            "aseStartDate": "2023-07-01",
            "indDate": "2023-12-30"
        }
    ],
    "message": "",
    "warning": "",
    "responseCode": "0"
}

Solution

  • If you are using Jackson for serialisation, putting JsonInclude(JsonInclude.Include.ALWAYS) on the SearchResponse class will always include all the class properties no matter their values. Thus, including the null values as well.