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

时间:2014-07-08 02:06:42

标签: 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.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"}

但有时候我没有isOn属性的值

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

2 个答案:

答案 0 :(得分:8)

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

  • 使用Boolean代替boolean原语(boolean值始终设为truefalse。)
  • 使用@JsonInclude(Include.NON_NULL)@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)配置Jackson不要序列化空值,具体取决于版本。

答案 1 :(得分:5)

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

@JsonInclude(JsonInclude.Include.NON_DEFAULT)注释用于版本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"}