使用Jackson转换Java对象时如何忽略可选属性 [英] How an optional property can be ignored when using jackson to convert Java object

查看:185
本文介绍了使用Jackson转换Java对象时如何忽略可选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson 1.9.2(org.codehaus.jackson)从Java对象转换为匹配的JSON构造.这是我的Java对象:

I'm using Jackson 1.9.2(org.codehaus.jackson) to convent from Java object to matching JSON construct. Here is my java object:

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

如果我进行了以下转换,我会得到想要的结果.

If I did the following conversion, I'd get the result I want.

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

jsonString就像:

jsonString would be like:

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

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

But sometimes I don't have the value of isOn property

ColorLight light = new ColorLight();
light.setType("red");
light.setValue("255");

但是jsonString仍然像:

But the jsonString is still like:

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

"isOn:false"是Java布尔类型的默认值,我不希望它存在. 我如何在这样的最终json构造中删除isOn属性?

Where "isOn:false" is default value of Java boolean type which I don't want it be there. How can I remove the isOn property in the final json construct like this?

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

推荐答案

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

To skip the value if it's not present:

  • 使用Boolean代替boolean原语(boolean值始终设置为truefalse).
  • 根据版本,配置Jackson不使用@JsonInclude(Include.NON_NULL)@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)序列化null.
  • Use Boolean instead of the boolean primitive (boolean values are always set to true or false).
  • Configure Jackson not to serialize nulls by using @JsonInclude(Include.NON_NULL) or @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL), depending on the version.

这篇关于使用Jackson转换Java对象时如何忽略可选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆