我有一个如下所示的类:-
@JsonSerialize(include = Inclusion.NON_EMPTY)
public class JsonPojo {
private int intVal;
private String strVal;
public int getIntVal() {
return intVal;
}
public void setIntVal(int intVal) {
this.intVal = intVal;
}
public String getStrVal() {
return strVal;
}
public void setStrVal(String strVal) {
this.strVal = strVal;
}
}
如果我有一个 JsonPojo 实例,其中未设置 int 字段,那么在将其转换为 json 时,jackson 会为其分配默认值 0,如下所示:-
public static void main(String[] args) {
JsonPojo jsonPojo = new JsonPojo();
jsonPojo.setStrVal("Hello World");
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
String json = mapper.writeValueAsString(jsonPojo);
System.out.println(json);
} catch (Exception e) {
}
}
这将输出:- {"intVal":0,"strVal":"Hello World"}
如果未设置 intVal
而不将 intVal
的数据类型转换为 ,有没有一种方法可以忽略 Json 输出中的
?如果我将 intVal
整数intVal
转换为 Integer,则当未设置此值时它将为 null 并且执行 JsonSerialize(include = Inclusion.NON_EMPTY)
将跳过 intVal
在转换为 json 的过程中。
但我想知道是否可以在不将 intVal
转换为 Integer
的情况下实现相同的行为?
我正在使用 jackson 1.9。
最佳答案
Inclusion.NON_EMPTY
应该符合您的预期。来自文档:
Value that indicates that only properties that have values that values that are null or what is considered empty are not to be included.
Java 原语 int
默认为 0(这被认为是空的)。所以如果你从未设置它或者你将它设置为 0 输出应该是1.9 上的一个问题
您可以尝试以下方法,也许可以在 1.9 上使用:
@JsonInclude(Include.NON_DEFAULT)
private int intVal;
并删除 include = Inclusion.NON_EMPTY
如果 0 是一个有效值,您可以向您的 pojo 添加一个标志。在你调用 setter 时,标志应该变为 true:
@JsonIgnore
public boolean set = false;
public Integer getIntVal() {
if (!set) {
return null;
}
return Integer.valueOf(intVal);
}
public void setIntVal(int intVal) {
set = true;
this.intVal = intVal;
}
关于java - 使用 jackson 将对象转换为json时忽略未设置原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36468620/