Java most efficiently handle non-existing JSON object properties

356 views Asked by At

I am trying to have my code catch and handle non-existing object properties.

To handle this error I created below code. Which I find very inefficient, clumsy and ugly. What am I supposed to do when I have to check more properties? copy paste the code for each property? It's repetitive, clumsy and slow most of all.

My code iterates over 40,000 items+, which I aim to do as fast as possible. Continuesly checking for object properties null value doesn't help the processing time.

String description;
       if(items.getDescription() != null){
           description = items.getDescription();
       } else{
           description = null;
       }

The Question:

How can I most efficiently check for multiple properties their existence (preferable also empty "")?

I read into setting string default values with annotations or something. Use Java's assert function (not entirely sure what it does). All other "solutions" I found were the same as I created above. !=null.

Background-info:

the object is created from a serialized JSON object. This object comes from an API over HTTP web request. I have no control over the api thus can't change its output. I have to check for possible null, empty and non-existing properties.

edit: providing currently used code.

JSONObject httpJSONObject = new JSONObject(result);
            itemRoot items = new Gson().fromJson(httpJSONObject.toString(), itemRoot.class);
            /*String description;
            if(items.getDescription() != null){
                description = items.getDescription();
            } else{
                description = null;
            }*/

            String query = "INSERT INTO item VALUES('" + items.getName().replaceAll("'","''") +
                    "','" + items.getDescription() +

Nullpointer error at very last line items.getDescription. I checked. When I use the !=null and set a value then everything is, of course, fine.

0

There are 0 answers