Home » Android » java – How to test if a JSONObject is null or doesn't exist

java – How to test if a JSONObject is null or doesn't exist

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a set of JSONObject values which i receive from a server and operate on. Most times I get a JSONObject with a value (let’s say statistics) and sometimes, it returns an Error object with a code and a description of the error.

How do I structure my code so that it doesn’t break if it returns the error. I thought I could do this, but doesn’t work.

public void processResult(JSONObject result) {
    try {
        if(result.getJSONObject(ERROR) != null ){
            JSONObject error = result.getJSONObject(ERROR);
            String error_detail = error.getString(DESCRIPTION);
            if(!error_detail.equals(null)) {
                //show error login here
            }
            finish();
        }
        else {
            JSONObject info = result.getJSONObject(STATISTICS);
            String stats = info.getString("production Stats"));
        }
    }
}
How to&Answers:

Use .has(String) and .isNull(String)

A conservative usage could be;

    if (record.has("my_object_name") && !record.isNull("my_object_name")) {
        // Do something with object.
      }

Answer:

In JSONObject there is a ‘Has’ method that you can do to Determaine the key.

I have no idea if this will work but it looks Credible.

public void processResult(JSONObject result) {

    if(result.has("ERROR"))
    {
        JSONObject error = result.getJSONObject("ERROR")
        String error_detail = error.getString("DESCRIPTION");

        if(error_detail != null)
        {
            //Show Error Login
            finish();
        }
    }
    else if(result.has("STATISTICS"))
    {
        JSONObject info = result.getJSONObject("STATISTICS");
        String stats = info.getString("Production Stats");

        //Do something
    }
    else
    {
        throw new Exception("Could not parse JSON Object!");
    }
}

Answer:

It might be little late(it is for sure) but posting it for future readers

You can use JSONObject optJSONObject (String name) which will not throw any exception and

Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.

so you can do

JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
      // it's an error , now you can fetch the error object values from obj
}

or if you just want to test nullity without fetching the value then

if( result.optJSONObject("ERROR")!=null ){
    // error object found 
}

There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.
e.g

String optString (String name, String fallback)

Returns the value mapped by name if it exists, coercing it if
necessary, or fallback if no such mapping exists.

where coercing mean, it will try to convert the value into String type


A modified version of the @TheMonkeyMan answer to eliminate redundant look-ups

public void processResult(JSONObject result) {
    JSONObject obj = null;
    if( (obj = result.optJSONObject("ERROR"))!=null ){
       //^^^^ either assign null or jsonobject to obj
      //  if not null then  found error object  , execute if body                              
        String error_detail = obj.optString("DESCRIPTION","Something went wrong");
        //either show error message from server or default string as "Something went wrong"
        finish(); // kill the current activity 
    }
    else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
        String stats = obj.optString("Production Stats");
        //Do something
    }
    else
    {
        throw new Exception("Could not parse JSON Object!");
    }
}

Answer:

It is sometimes more convenient and less ambiguous to have a NULL object than to use Java’s null value.

  • JSONObject.NULL.equals(null) returns true.

    JSONObject.NULL.toString()returns “null”.

Example:

System.out.println(test.get(“address”).equals(null)); // Preferred way
System.out.println(test.getString(“address”).equals(“null”));

source — JSONObject oracle docs