[英]Jackson Displaying fields in Json response
自最近兩天以來,我一直在努力解決一個問題。 我有一個Integer
對象和一個Float
對象,如果它是0
,我不想在JSON
響應中顯示。 我正在嘗試使用@JsonInclude(value=Include.NON_NULL)
來實現這一點,但是它似乎沒有用。
有人有什么建議可以解釋我在這里做錯了什么嗎?
可以說模型類是這樣的:
@JsonInclude(value = Include.NON_NULL)
public class myClassInfo {
String originalQuery;
String normalizedQuery;
Long id;
Integer performanceStatus;
Float atcPercentage;
Integer ruleOn;
Integer ruleOff;
}
我有相應的getter和setter方法。 我只想顯示atcPercentage
, ruleOn
和ruleOff
除非它不為0
。 我該怎么做? 我希望這種解釋有助於理解我的問題。 我試過NON_NULL
,它似乎沒有用。 我的理解是,如果我在類的開頭定義了JsonInclude
,那應該適用於所有字段。 如果我錯了,請糾正我。
您可以編寫自己的過濾器並按以下方式使用它:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonApp {
public static void main(String[] args) throws Exception {
ClassInfo classInfo = new ClassInfo();
classInfo.setId(0L);
classInfo.setAtcPercentage(0F);
classInfo.setPerformanceStatus(0);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(classInfo));
}
}
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = ZeroNumberFilter.class)
class ClassInfo {
private Long id;
private Integer performanceStatus;
private Float atcPercentage;
// getters, setters
}
class ZeroNumberFilter {
@Override
public boolean equals(final Object obj) {
if (obj instanceof Number) {
final Number number = (Number) obj;
return Double.compare(number.doubleValue(), 0) == 0;
}
return false;
}
}
打印{}
-空對象。 當我們將所有值更改為1
,它會打印:
{"id":1,"performanceStatus":1,"atcPercentage":1.0}
Include.NON_NULL
僅過濾具有null
值的屬性。 您可以使用Include.NON_DEFAULT
但是在這種情況下,您應該更改POJO
並為所有字段聲明默認值:
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
class ClassInfo {
private Long id = 0L;
private Integer performanceStatus = 0;
private Float atcPercentage = 0F;
// getters, setters
}
但是,如果您的業務邏輯依賴於某個地方的null
值,則此解決方案可能會有一些缺點。
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.