Spring:返回对象中的布尔变量

Spring: boolean variables in objects get returned

假设我有一个对象:

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

    public Foods() {}

    @Id
    @JsonProperty
    private String id;

    @JsonProperty
    private String name;

    @JsonProperty
    private Double calories;

    @JsonProperty
    private boolean sweet;

    }

现在,在我的 Spring REST API 调用中,我只填充食物的 "name" 字段和 return 它。

我得到这个作为 return JSON:

  {
    "name": "Strawberry Pies",
    "sweet": false
  }

您可以看到,因为卡路里没有填充,所以 JSON 没有 return。我猜 "sweet" 字段被填充是因为布尔值的默认值为 false。

但是我不希望 JSON 字符串为 return "sweet" 布尔值 false,如果它首先没有填充的话。有办法吗?

注释您的字段(或 属性 getter/setter)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private boolean sweet;

NON_DEFAULT 的 javadoc 指出

Value that indicates that only properties that have values that differ from default settings (meaning values they have when Bean is constructed with its no-arguments constructor) are to be included.

private boolean sweet;

默认值为 false。如果这是您序列化的对象的字段值,JSON 将不包含它。

同样,如果你

private boolean sweet = true;

并且相应对象的字段值为 true,生成的 JSON 也不会包含它。