JSONObject jsonObj = {"a":"1","b":null}
CASE 1 : jsonObj.getString("a") returns "1";
CASE 2 : jsonObj.getString("b") return nothing ;
CASE 3 : jsonObj.getString("c") throws error;
How to make case 2 and 3 return null
and not "null"
?
To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.
Try with json. isNull( "field-name" ) . I would go further and say to NEVER use has(KEY_NAME), replacing those calls to ! isNull(KEY_NAME).
Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().
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));
}
}
you can use optString("c")
or optString("c", null)
as stated in the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With