简体   繁体   English

检查Object的错误是null

[英]Error checking Object is null

I got a HttpResponse which gets a json response. 我得到了一个获得json响应的HttpResponse。

Now if the json response contains data it all works fine, but whenever the json is null my application crashes. 现在,如果json响应包含数据,它一切正常,但每当json为null时,我的应用程序崩溃。

I've been trying to following code but with no avail. 我一直在尝试遵循代码,但没有用。

(sb = json response) (sb = json回复)

Object result11 = sb;
Log.d("Result11", result11.toString());

if (result11 == JSONObject.NULL)
    Log.d("if", "I am NULL");
else
    Log.d("else", "I am not null");

I tried comparing result11 to: 我尝试将result11比较为:

null, "", "null", JSONObject.NULL

It always returns "I am not null" 它总是返回“我不是空”

Whilst the log says that Resul11 = null. 虽然日志说Resul11 = null。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance. 提前致谢。

EDIT: 编辑:

Object result11 = sb;
            Log.d("Result11", result11.toString());

            StringBuilder test = (StringBuilder)result11;

            if (test.toString().equals("null"))
                Log.d("if", "I am NULL");
            else
                Log.d("else", "I am not null");

SOLUTION by @Mark Byers 解决方案由@Mark Byers提供

test.toString().trim().equals("null") 

results in "I AM NULL" 导致“我是空”

You don't have a null . 你没有null You have a StringBuilder that when converted to a String contains the value "null" . 你有一个StringBuilder ,转换为String包含值"null"

To compare strings do not use the == operator. 要比较字符串,请不要使用==运算符。 Instead you should convert to a String and use the equals method. 相反,您应该转换为String并使用equals方法。

StringBuilder stringBuilder = (StringBuilder)result11;
String trimmed = stringBuilder.toString().trim();
if (trimmed.equals("null")) { ... }

The == operator compares the references and only returns true if the operands are references to the same object (or both null references). ==运算符比较引用,如果操作数是对同一对象(或两个空引用)的引用,则仅返回true。 The equals method compares the values. equals方法比较值。

Related 有关

如果你得到一个null结果与空指针比较: result11 == null

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

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