In a JSON "object" (aka dictionary), there are two ways to represent absent values: Either have no key/value pair at all, or have a key with the JSON value null.

So you either use .add with a proper value what will get translated to null when you build the JSON, or you don't have the .add call.

Answer from gnasher729 on Stack Exchange
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!");
    }
}
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › org.json.jsonobject.null
JSONObject.Null Property (Org.Json) | Microsoft Learn
A sentinel value used to explicitly define a name with no value. Unlike null, names with this value: <ul> <li>show up in the #names array <li>show up in the #keys iterator <li>return true for #has(String)<li>do not throw on #get(String)<li>are ...
🌐
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.
🌐
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.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.
🌐
GitHub
github.com › stleary › JSON-java › issues › 667
Creating JSONObject from Map vs String misses null values · Issue #667 · stleary/JSON-java
February 21, 2022 - If we create a JSONObject from a string containing null values, those are parsed internally as JSONObject.NULL [see 1]. However, when creating a JSONObject from a Map, null values are ignored [see ...
Author   alexisml
Find elsewhere
🌐
GitHub
gist.github.com › iperdomo › 2867928
Handling null values (JSONObject) · GitHub
false false true true org.codehaus.jettison.json.JSONException: JSONObject["nonexistent"] not found.
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonobject
org.json.JSONObject.isNull java code examples | Tabnine
public List<MyItem> read(InputStream inputStream) throws JSONException { List<MyItem> items = new ArrayList<MyItem>(); String json = new Scanner(inputStream).useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { String title = null; String snippet = null; JSONObject object = array.getJSONObject(i); double lat = object.getDouble("lat"); double lng = object.getDouble("lng"); if (!object.isNull("title")) { title = object.getString("title"); } if (!object.isNull("snippet")) { snippet = object.getString("snippet"); } items.add(new MyItem(lat, lng, title, snippet)); } return items; }
🌐
Rip Tutorial
riptutorial.com › jsonobject.null
Java Language Tutorial => JSONObject.NULL
JSONObject.NULL is a sentinel value used to explicitly define a property with an empty value.
🌐
GitHub
github.com › stleary › JSON-java › issues › 382
JSONObject.put(String, Object) doesn't store null value · Issue #382 · stleary/JSON-java
November 16, 2017 - According to the JSON specification, a JSON value may be null. However, JSONObject.put(String, Object) doesn't store this. It is therefore not possible to make a distinction between the object ...
Author   RaySinnema
🌐
Kotlin Discussions
discuss.kotlinlang.org › android
Kotlin JSONObject$Null Bug - Android - Kotlin Discussions
April 5, 2018 - Hey, Im new here, so sorry if i posted this in the wrong section! I just found this bug for Kotlin while using the org.json library. When JSON returns null, it gives a JSONObject$Null While checking for null, == fails, and .equals warns to use == My code: fun testNullJSON(jsonObject: JSONObject, valueKey: String){ val jsonArray = jsonObject.getJSONArray(valueKey) for(i in 0 until jsonArray.length()) { val jsonArrayValue = jsonArray[i] ?: continue // NOTE: First null check here w...
🌐
ArduinoJson
arduinojson.org › version 6 › api › jsonobject › isnull()
JsonObject::isNull() | ArduinoJson 6
ArduinoJson 6 user’s manual. The function JsonObject::isNull() tests if the JsonObject is valid.
🌐
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 ...
🌐
Oracle
docs.oracle.com › middleware › maf222 › mobile › api-ref › oracle › adfmf › json › JSONObject.html
JSONObject (Oracle Fusion Middleware Java API Reference for Oracle Mobile Application Framework)
The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.
🌐
Couchbase
docs.couchbase.com › mobile › 3.0.0 › couchbase-lite-java › org › json › JSONObject.html
JSONObject (Couchbase, Inc. Enterprise Edition License Agreement 3.0.0-189)
If the object is null or , returns NULL. If the object is a JSONArray or JSONObject, no wrapping is necessary. If the object is NULL, no wrapping is necessary. If the object is an array or Collection, returns an equivalent JSONArray. If the object is a Map, returns an equivalent JSONObject.