Home > OS >  Remove null attributes from request body Spring Boot
Remove null attributes from request body Spring Boot

Time:12-08

I'm new to spring boot and was referring to this article. It asks to add @JsonInclude(Include.NON_NULL) annotation to remove null attributes from response body, however I'm interested in removing null attributes from request body. Please suggest how can I achieve that.

The request body is:

{
    "userUuid": "2u9k2ld8f-ghj47dhj",
    "suggestion": null
}

and the request DTO class is:

@Data
@NoArgsConstructor
public class UserRequestDTO implements Serializable {
    private String userUuid;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String suggestion;
}

Clearly it is not working for me. When I stringify and print the request body, it includes suggestion attr which is null. Thank you for any help.

CodePudding user response:

Well... Do not use toString() use Jackson ObjectMapper. So like:

var objectMapper = new ObjectMapper();
var dto = objectMapper.readValue(JSON, UserRequestDTO.class);
var strNoNullFields = objectMapper.writeValueAsString(dto);

That way the annotation is working.

Anyway this is not something very optimal. You might want to re-think your design how to calculate checksum (your question smells a bit like XY-problem).

CodePudding user response:

I need to generate the checksum of the payload excluding the null attrs. I do not want to replace null attr rather remove it. To generate the signature I will to doing .toString() on the request body

I think you are looking for a request has dinamyc attributes.

Try use a HashMap<String,Object> on parameters.

Other simple way is overriding toString() from DTO and ignore null attrs.

Sugestions: Besides using this only for logging I think both is bad practice could be better create a method generateSignature() handles all rules of this.

  • Related