將對象轉換爲JSON忽略不設置原語類型我有一個類看起來像下面: -同時使用傑克遜
@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,如下圖所示傑克遜分配一個默認的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
的數據類型爲Integer
時,Json輸出中的?如果我將intVal
轉換爲Integer,那麼當這個值沒有設置時,它將爲空&做JsonSerialize(include = Inclusion.NON_EMPTY)
在轉換到json期間將跳過intVal
。
但我想知道是否可以實現相同的行爲,而無需將intVal
從int
轉換爲Integer
?
我正在使用傑克遜1.9。
你的問題很有趣。我向作者申請了一個Jsonfilter,希望這可以提供幫助。 –