1

Setting default value for boolean as true

This is the dto clas which is having boolean value in it.

DTO class

public class SensitivityDto extends AuditableEntity implements Serializable {
    private static final long serialVersionUID = 1L;


    private long sensitivityId;
    @JsonIgnore
    private boolean isSelected;

    public SensitivityDto() {
    }
    /** other getter/setters */
    public boolean isIsSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

}

input json

{
  "sensitivity": {
    "sensitivityId": 100,
    "isSelected": "true", // if not passing this field always its treated as null.

  }
}

Controller

public @ResponseBody ResultDecorator saveLabResultCultureDetails(@RequestBody SensitivityDto sensitivityDto) throws  Exception {

}

How can I set boolean value default to true, So that if this value is not present in json, then it should not be false it should be true.

1 Answer 1

3

What about?

@JsonIgnore
private boolean isSelected = true;

From the comment:

then even I'm sending false in json, its takng as true

You have to remove @JsonIgnore and use @JsonAutoDetect, as follows:

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class SensitivityDto extends AuditableEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    private long sensitivityId;


    private boolean isSelected = true;

    public SensitivityDto() {
    }

    /** other getter/setters */
    public boolean isIsSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

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

4 Comments

then even I'm sending false in json, its takng as true
Why did you add the @JsonIgnore annotation if you don't want to ignore it?
Response I don't need that. So added. I required that in request.
Then remove the @JsonIgnore and use a @JsonView for your response, where that field is excluded in the response. With @JsonIgnore you can't distinguish between request and response, it will always be ignored in JSON serialization or deserialization.

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.