abdul rashid
abdul rashid

Reputation: 750

JSONObject value null check failed with empty() and ==null why

I am having following json

{"signature": null, "state": "eyJjc3OiIifQ", "tokenId": null, "error": "EXCEPTION_REQUEST_CANCELLED"}

from jsonObject of JSONObject jsonObject = new JSONObject(authMeta);

I tried checking

if(jsonObject.get("signature") == null) {} else {}

condition IF failed and code went to else block. tried another method

if(jsonObject.get("signature").toString().isEmpty())

Above also failed.

if(jsonObject.get("signature").equals(null))

Worked.

Following code worked.

jsonObject.isNull("signature")

I checked inside isNull Method, i found following.

public boolean isNull(String key) {
    return JSONObject.NULL.equals(this.opt(key));
}

Unable to understand why null is different ?

Upvotes: 0

Views: 1656

Answers (1)

LHCHIN
LHCHIN

Reputation: 4009

Because org.json.JSONObject.get(java.lang.String key) is going to return java.lang.Object.
So...

jsonObject.get("signature") == null

This doesn't work because == in Java is used to compare primitives and objects. And == compare two objects based on memory reference. so == operator will return true only if two object reference it is comparing represent exactly same object.

jsonObject.get("signature").equals(null)

This works because we use the equals() method to compare objects in Java. In order to determine if two objects are the same, equals() compares the values of the objects’ attributes.

Let's look at following example:

System.out.println(obj.get("signature").getClass()); //class org.json.JSONObject$Null
System.out.println(obj.get("state").getClass()); //class java.lang.String

System.out.println(JSONObject.NULL.getClass()); //class org.json.JSONObject$Null

You can see that the first statement returns a Object and the second one returns a String. That's why you using equals() for null check works.

Upvotes: 1

Related Questions