简体   繁体   中英

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

I have JSONObject with a set of fields, not setting the field in JSONObject if it has a null value in the angular app. So I am doing a null check of each field before getting the value of that in spring-boot as below.

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

Is there any better way to write this null check in a single statement instead of If-Else condition?

You can get rid of if-else conditions by using below logic:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM