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 from BrantApps on Stack Overflow
Top answer
1 of 7
142

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.
      }
2 of 7
17

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!");
    }
}
🌐
ArduinoJson
arduinojson.org › version 6 › api › jsonobject › isnull()
JsonObject::isNull() | ArduinoJson 6
JsonObject::isNull() tests whether the JsonObject points to an object or not. You can use this function to: check if the object was successfully parsed, or · check if the object was successfully allocated. As an alternative, you can use the conversion to bool; for example, if(object) instead of if(!object.isNull()) bool isNull() const; JsonObject::isNull() returns a bool that tells if the JsonObject points to something: true if the JsonObject is null...
🌐
Processing
processing.org › reference › JSONObject_isNull_.html
isNull() / Reference / Processing.org - JSONObject
January 1, 2021 - Determines if the value associated with the key is null, that is has no defined value (false) or if it has a value (true). ... JSONObject json; void setup() { json = new JSONObject(); json.setInt("id", 0); json.setString("species", null); if ...
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonobject
org.json.JSONObject.isNull java code examples | Tabnine
/* package for test */ Object convertCloudResponse(Object result) { if (result instanceof JSONObject) { JSONObject jsonResult = (JSONObject) result; // We want to make sure we pass back a null result as null, and not a JSONObject if (jsonResult.isNull("result")) { return null; } result = jsonResult.opt("result"); } ParseDecoder decoder = ParseDecoder.get(); Object finalResult = decoder.decode(result); if (finalResult != null) { return finalResult; } return result; } } Returns true if this object has no mapping for name or if it has a mapping whose value is #NULL.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-check-if-a-json-object-is-empty-or-not-in-java
How can we check if a JSON object is empty or not in Java?\\n
Let's see the code to check if a JSON object is empty or not using the length() method: import org.json.JSONObject; import org.json.JSONException; public class CheckEmptyJsonObjectExample { public static void main(String[] args) throws JSONException { // Create a JSON object JSONObject jsonObj ...
🌐
GitHub
gist.github.com › iperdomo › 2867928
Handling null values (JSONObject) · GitHub
NullTest.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters · Show hidden characters · Copy link · Author · The result is: false false true true org.codehaus.jettison.json.JSONException: JSONObject["nonexistent"] not found.
Find elsewhere
🌐
Opencms
documentation.opencms.org › javadoc › core › org › opencms › json › JSONObject.Null.html
JSONObject.Null (OpenCms Core API, version 20.0)
JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined. ... There is only intended to be a single instance of the NULL object, so the clone method returns itself. ... A Null object is equal to the null value and to itself. ... Get the "null" string value. finalize, getClass, notify, notifyAll, wait, wait, wait
🌐
Rip Tutorial
riptutorial.com › jsonobject.null
Java Language Tutorial => JSONObject.NULL
If you need to add a property with a null value, you should use the predefined static final JSONObject.NULL and not the standard Java null reference. JSONObject.NULL is a sentinel value used to explicitly define a property with an empty value.
🌐
Stack Overflow
stackoverflow.com › questions › 26669742 › java-check-null-faile-for-result-of-jsonobject
json - Java check null faile for result of JSONObject - Stack Overflow
ok is null and your code is retuen false but thats null and must be return true 2014-10-31T08:01:05.96Z+00:00 ... @jJz please post the same code or atleast the json, and what exactly you want 2014-10-31T08:04:50.647Z+00:00 ... If I understand the problem correctly, you only want to the value of a property in the JSON if it's not null, "null" or empty.
🌐
Nih
ii.nlm.nih.gov › Web_API › doc › org › json › JSONObject.Null.html
JSONObject.Null (SKR REST API)
JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined.
🌐
Progress
docs.progress.com › bundle › abl-reference › page › IsNull-method-JsonObject.html
IsNull( ) method (JsonObject)
February 10, 2026 - Skip to main contentSkip to search · Powered by Zoomin Software. For more details please contactZoomin
🌐
Stack Overflow
stackoverflow.com › questions › 32582680 › how-to-check-json-object-is-null-or-not
How to check json object is null or not?
May 23, 2017 - $('input#emailId').blur( function() { $.ajax({ url:'/getUserByEmailOrPhone-'+$('#emailId').val()+'-'+$('#contactNumber').val(), type:'GET', data: 'json', success:function(json){ if (json.length == 0) { $('.email-check').append('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true" id="tt2" clientidmode="Static" runat="server" Visible="False"></span>'); } else{ alert('user exists'); $('.email-check').append('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true" id="tt2" clientidmode="Static" runat="server" Visible="False"></span>'); } } }); });