我正在使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我做了以下转换,我会得到我想要的结果.
ColorLight light = new ColorLight();
light.setType("red");
light.setIsOn("true");
light.setValue("255");
objectMapper mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString();
Run Code Online (Sandbox Code Playgroud)
jsonString会是这样的:
{"type":"red","isOn":"true", "value":"255"}
Run Code Online (Sandbox Code Playgroud)
但有时我没有isOn属性的值
ColorLight light = new ColorLight();
light.setType("red");
light.setValue("255");
Run Code Online (Sandbox Code Playgroud)
但是jsonString仍然像:
{"type":"red","isOn":"false", "value":"255"}
Run Code Online (Sandbox Code Playgroud)
其中"isOn:false"是Java布尔类型的默认值,我不希望它在那里.如何删除最终json构造中的isOn属性?
{"type":"red","value":"255"}
Run Code Online (Sandbox Code Playgroud)
要跳过该值,如果它不存在:
Boolean而不是boolean原语(boolean值始终设置为true或false).@JsonInclude(Include.NON_NULL)或序列化空值@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL),具体取决于版本.您可以使用@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)1.x注释标记您的类,该注释指示仅包含具有与默认设置不同的值的属性(意味着当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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"type":"value"}
Run Code Online (Sandbox Code Playgroud)