Java 如何在获取值之前对JSONObject中的每个元素进行空检查?

Java 如何在获取值之前对JSONObject中的每个元素进行空检查?,java,json,Java,Json,我有一个带有一组字段的JSONObject,如果JSONObject在angular应用程序中有空值,则不在JSONObject中设置字段。因此,在spring boot中获取每个字段的值之前,我将对每个字段进行空检查,如下所示 JSONObject exclusionObj = (JSONObject) exclusionArray.get(i); SampleBean sample = new SampleBean();

我有一个带有一组字段的JSONObject,如果JSONObject在angular应用程序中有空值,则不在JSONObject中设置字段。因此,在spring boot中获取每个字段的值之前,我将对每个字段进行空检查,如下所示

            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"));
            }

是否有更好的方法在单个语句中写入此空检查而不是If-Else条件?

您可以使用以下逻辑来消除If-Else条件:

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

为什么必须
sample.setName(null)是吗?
null
不是默认值吗?null是默认值。。为了更好地理解,我添加了它,而不是一个空行。只需反转条件,仅在不为null时设置<代码>如果(!ExclutionObj.isNull(“wtv”))sample.setWtv(…)确定。非常感谢。你能把它作为一个答案加上吗?这样我就可以投票了?