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!");
    }
}
🌐
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.
🌐
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
true if the JsonObject is null, false if the JsonObject is valid and points to an object. Example 1: parsing success: StaticJsonDocument<200> doc; deserializeJson(doc, "{\"hello\":\"world\"}"); JsonObject object = doc.as<JsonObject>(); ...
🌐
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.
🌐
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; }
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
the array value to which the specified name is mapped, or null if this object contains no mapping for the name · Throws: ClassCastException - if the value to which the specified name is mapped is not assignable to JsonArray type · JsonObject getJsonObject(String name) Returns the object value ...
Find elsewhere
🌐
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)
Returns the value mapped by name if it exists and is a JSONArray, or null otherwise. @NonNull public JSONObject getJSONObject​(@NonNull java.lang.String name) throws JSONException · Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
🌐
GitHub
github.com › stleary › JSON-java › issues › 296
JSONObject(Map) handling of null values has changed · Issue #296 · stleary/JSON-java
October 24, 2016 - Before 2010-12 the JSONObject-constructor public JSONObject(Map map) accepted null values in the map and transformed them to JSONObject.NULL i.e.: public static void main(String[] args) throws UnknownHostException { Map t...
Author   effad
🌐
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
🌐
GitHub
gist.github.com › iperdomo › 2867928
Handling null values (JSONObject) · GitHub
Handling null values (JSONObject) Raw · 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.
🌐
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
🌐
Grails
grails.github.io › grails2-doc › 2.3.x › api › org › codehaus › groovy › grails › web › json › JSONObject.Null.html
JSONObject.Null (Grails 2.3.11)
This page has moved to https://grails.apache.org/docs/2.3.x/api/org/codehaus/groovy/grails/web/json/JSONObject.Null.html
Top answer
1 of 2
23

You can use get() instead of getString(). This way an Object is returned and JSONObject will guess the right type. Works even for null. Note that there is a difference between Java null and org.json.JSONObject$Null.

CASE 3 does not return "nothing", it throws an Exception. So you have to check for the key to exist (has(key)) and return null instead.

public static Object tryToGet(JSONObject jsonObj, String key) {
    if (jsonObj.has(key))
        return jsonObj.opt(key);
    return null;
}

EDIT

As you commented, you only want a String or null, which leads to optString(key, default) for fetching. See the modified code:

package test;

import org.json.JSONObject;

public class Test {

    public static void main(String[] args) {
        // Does not work
        // JSONObject jsonObj  = {"a":"1","b":null};

        JSONObject jsonObj  = new JSONObject("{\"a\":\"1\",\"b\":null,\"d\":1}");

        printValueAndType(getOrNull(jsonObj, "a")); 
        // >>> 1 -> class java.lang.String

        printValueAndType(getOrNull(jsonObj, "b")); 
        // >>> null -> class org.json.JSONObject$Null

        printValueAndType(getOrNull(jsonObj, "d")); 
        // >>> 1 -> class java.lang.Integer

        printValueAndType(getOrNull(jsonObj, "c")); 
        // >>> null -> null
        // throws org.json.JSONException: JSONObject["c"] not found. without a check
    }

    public static Object getOrNull(JSONObject jsonObj, String key) {
        return jsonObj.optString(key, null);
    }

    public static void printValueAndType(Object obj){
        System.out.println(obj + " -> " + ((obj != null) ? obj.getClass() : null)); 
    }
}
2 of 2
8

you can use optString("c") or optString("c", null)

as stated in the documentation

🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.M2 › api › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.M2 API)
the value or null · public JSONObject getJSONObject(String name) throws JSONException · Returns the value mapped by name if it exists and is a JSONObject. Parameters: name - the name of the property · Returns: the value · Throws: JSONException - if the mapping doesn't exist or is not a JSONObject.