0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.