简体   繁体   中英

checking a string for null in java

I have this:

String object = "";
try {
    object = data.getString("url");
    System.out.println("Url Object:" + object);
}
catch (JSONException e) {
    e.printStackTrace();
}  

System.out.println("object is:" + object);
if (object!= null ) {
    // doSomething
} else {
    // is Null
}

and although this is printed:

object is: null

The code enters the if condition and not the else.

What am I missing?

EDIT: where data is a JSONObject. I now want to test the case that url is null. Therefore, I know that data is null and I can see it printed.

Your code is an anti pattern. Move the code that processes 'string' inside the 'try' block. Don't just catch exceptions and then continue as though they didn't happen, and have to sort out again whether you're in a valid state. That's what the 'try' block is for. If you're still in it, you're in a valid state.

Don't initialize your String object to "" if you want it to be null if the json parsing bits fail.

Change your top line to:

String object = null;

More to the point, check out https://stackoverflow.com/a/21246501/599075

Please note that getString(..) is returning "null" (as a String , when ob.toString() do that). So when you assign it to object , it is a String: "null" , not null .

To correct your code one way would be:

if (!object.equals("null")) {
   // doSomething
} else {
   // is Null
}

Another solution would be setting object to be null if getString() returns "null" :

if (data.getString("url").equals("null"))
    object = null;

The only explanation to your case is that the data.getString("url"); is returning a "null" String value.By the way I recommend you these points :

  • Initialize your object by a null reference ( String object = null; )

  • Change the if condition ( if(object!=null) && !object.isEmpty() )

    Otherwise, try to print entirely the content of the data object to the console so you can check the json content you are trying to parse. (Sorry if I made some language mistakes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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