简体   繁体   English

JSONObject 值 null 检查失败,empty() 和 ==null 为什么

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

I am having following json我正在关注 json

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

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

I tried checking我试过检查

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

condition IF failed and code went to else block.条件 IF 失败,代码转到 else 块。 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.我检查了 isNull 方法,我发现了以下内容。

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

Unable to understand why null is different ?无法理解为什么 null 不同?

Because org.json.JSONObject.get(java.lang.String key) is going to return java.lang.Object .因为org.json.JSONObject.get(java.lang.String key)将返回java.lang.Object
So...所以...

jsonObject.get("signature") == null

This doesn't work because == in Java is used to compare primitives and objects.这是行不通的,因为 Java 中的==用于比较原语和对象。 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.所以==运算符只有在它比较的两个对象引用代表完全相同的对象时才会返回 true。

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

This works because we use the equals() method to compare objects in Java.这是有效的,因为我们使用equals()方法来比较 Java 中的对象。 In order to determine if two objects are the same, equals() compares the values of the objects' attributes.为了确定两个对象是否相同, equals()比较对象的属性值。

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 .您可以看到第一个语句返回一个Object ,第二个语句返回一个String That's why you using equals() for null check works.这就是为什么您使用equals()进行空检查的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM