簡體   English   中英

Jackson在Json響應中顯示字段

[英]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方法。 我只想顯示atcPercentageruleOnruleOff除非它不為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM