Issue
I have a Spring Boot REST API and one of the endpoints takes requests that include a body, like this:
@GetMapping("/search")
public List<ItemDto> searchDevice(@RequestBody ItemDto itemDto){
// code
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ItemDto {
//other fields
@JsonProperty(value = "status")
private boolean status;
// getters and setters
}
So my problem is this: when I send a request not containing status
it defaults to false
, which is not the behaviour I need. I want status to be null
, when it is not specified. How can I achieve this?
Another interesting behaviour is that status
is false
even when I specify it in the query as "status": null
As you can see, I already tried to use the annotations @JsonInclude
and @JsonProperty
, that I've seen recommended in similiar questions, but they are not working for me. The boolean still defaults to false
. Is there any other fix for this?
Solution
boolean
is a primitive type which means it is not a Java object. As such it cannot be null
, just true or false. You can just replace it by the Java object equivalent which is Boolean
and then it will be able to be null
. In Java there is boxing an unboxing which allow seamless conversion between primitive type and Java object equivalent (or wrapper) when needed, so you can still do if(yourBoolean)
if it's a Boolean
but be aware that this can throw NPE if yourBoolean
is null
.
Note that it is not usually good practice to do that, you shouldn't have a different logic when the boolean isn't here as when it's null
, as it is not really a boolean anymore. If you have control over the input and you really have 3 states, then look into using an enum as it might be a better choice (or you can use 2 boolean).
Answered By - Nyamiou The Galeanthrope
Answer Checked By - Timothy Miller (JavaFixing Admin)