簡體   English   中英

如何在獲取值之前對 JSONObject 中的每個元素進行 null 檢查?

[英]How to do null check of each element in JSONObject before getting value?

我有帶有一組字段的 JSONObject,如果它在 angular 應用程序中具有 null 值,則不設置 JSONObject 中的字段。 因此,在獲取 spring-boot 中的值之前,我正在對每個字段進行 null 檢查,如下所示。

            JSONObject exclusionObj = (JSONObject) exclusionArray.get(i);
            SampleBean sample  = new SampleBean();

            if(exclusionObj.isNull("name")) {
                sample.setName(null);
            }else{
                sample.setName(exclusionObj.getString("name"));
            }

            if(exclusionObj.isNull("designation")) {
                sample.setDesignation(null);
            }else{
                sample.setdesignation(exclusionObj.getString("designation"));
            }

            if(exclusionObj.isNull("dept")) {
                sample.setDept(null);
            }else{
                sample.setDept(exclusionObj.getInt("dept"));
            }

有沒有更好的方法來編寫這個 null 檢查在單個語句中而不是 If-Else 條件?

您可以使用以下邏輯擺脫 if-else 條件:

Iterator<String> keys = exclusionObj.keys();
    while(keys.hasNext()) {
        if (!exclusionObj.isNull(keys.next())) {
            sample.setName(exclusionObj.getString(keys.next()));
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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