Spring MVC Rest Service JSON - 将boolean的默认值设置为true

时间:2017-01-08 09:12:38

标签: java json spring rest spring-mvc

boolean的默认值设为true

这是dto clas,其中包含布尔值。

DTO课程

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;
    }

}

输入json

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

  }
}

控制器

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

}

如何将布尔值默认设置为true, 因此,如果json中不存在此值,则它不应为false,应该为true。 < / p>

1 个答案:

答案 0 :(得分:2)

怎么样?

@JsonIgnore
private boolean isSelected = true;

来自评论:

  

然后即使我在json发送false,它的takng为真

您必须删除@JsonIgnore并使用@JsonAutoDetect,如下所示:

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;
    }

}