使用jackson转换Java对象时如何忽略可选属性

使用jackson转换Java对象时如何忽略可选属性,java,json,jackson,Java,Json,Jackson,我使用Jackson 1.9.2(org.codehaus.Jackson)将Java对象转换为匹配的JSON构造。这是我的java对象: Class ColorLight { String type; boolean isOn; String value; public String getType(){ return type; } public setType(String type) { this.typ

我使用Jackson 1.9.2(org.codehaus.Jackson)将Java对象转换为匹配的JSON构造。这是我的java对象:

Class ColorLight {
    String type;
    boolean isOn;
    String value;

    public String getType(){
        return type;
    }

    public setType(String type) {
        this.type = type;
    }

    public boolean getIsOn(){
        return isOn;
    }

    public setIsOn(boolean isOn) {
        this.isOn = isOn;
    }

    public String getValue(){
        return value;
    }

    public setValue(String value) {
        this.value = value;
    }
}
如果我做了下面的转换,我会得到我想要的结果

ColorLight light = new ColorLight();
light.setType("red");
light.setIsOn("true");
light.setValue("255");
objectMapper mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString();
jsonString类似于:

{"type":"red","isOn":"true", "value":"255"}
但有时我没有财产的价值

ColorLight light = new ColorLight();
light.setType("red");
light.setValue("255");
但是jsonString仍然是这样的:

{"type":"red","isOn":"false", "value":"255"}
其中“isOn:false”是Java布尔类型的默认值,我不希望它出现在那里。 我如何删除最终json构造中的isOn属性

{"type":"red","value":"255"}

如果该值不存在,则跳过该值:

  • 使用
    Boolean
    而不是
    Boolean
    原语(
    Boolean
    值始终设置为
    true
    false
  • 根据版本,使用
    @JsonInclude(Include.NON_NULL)
    @JsonSerialize(Include=JsonSerialize.Inclusion.NON_NULL)
    配置Jackson不序列化NULL

您可以在1.x注释中使用
@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
标记您的类,该注释指示只包括具有不同于默认设置的值的属性(即使用无参数构造函数构造Bean时的值)

@JsonInclude(JsonInclude.Include.NON_默认值)
注释用于版本2.x

以下是一个例子:

public class JacksonInclusion {

    @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
    public static class ColorLight {
        public String type;
        public boolean isOn;

        public ColorLight() {
        }

        public ColorLight(String type, boolean isOn) {
            this.type = type;
            this.isOn = isOn;
        }
    }

    public static void main(String[] args) throws IOException {
        ColorLight light = new ColorLight("value", false);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(light));
    }
}
输出:

{"type":"value"}