3

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
}

The DTO looks like this:

@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?

2
  • 3
    boolean is a primitive type. primitives can not be null. You can use the wrapper type Boolean, though. Commented Jan 8, 2021 at 12:39
  • Oh wow, thank you this helped! I can't believe I missed that Commented Jan 8, 2021 at 12:45

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

You have to give the Boolean wrapper for the status variable

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ItemDto {

@JsonProperty(value = "status")
private Boolean status;

// getters and setters
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.