2

I have a json in which userId property is coming as string "null" -

"userId":"null"

I have a method which checks whether my string is null or not -

public static boolean isEmpty(String value) {
    return value == null || value.isEmpty();
}

But every time my above method returns back me as false for above userId? It should true since userId is null. Is there any other api in Guava or Apache Commons which can do this?

john
  • 11,311
  • 40
  • 131
  • 251
  • 2
    Have you also checked for the string equaling "null" eg value.equals("null")? – copeg Apr 07 '15 at 19:29
  • @copeg Instead of doing that way - Is there any other library which can do this for me? – john Apr 07 '15 at 19:30
  • 1
    @david There may be libraries that check for `null` and empty, but I don't think they check for the string "null". – Sirac Apr 07 '15 at 19:31
  • Your method returns `false` because the string is not `null` or empty - it is `"null"` - in other words, a string consisting of 4 characters. Note that `"null"` is not the same as `null`. If you meant "no value", the JSON should have looked like this: `"userId":null` (note: no quotes around `null`). – Jesper Apr 07 '15 at 19:33
  • You should try not to have a string with value "null" in your json in the first place... – assylias Apr 08 '15 at 22:27

3 Answers3

8

The value null is not equal to the String "null". null means that a given object has not been assigned a value, where the String "null" is a valid object. It contains the characters n u l l, which is a valid value for a String. You need to also check if the value is the literal string "null" in order to do what you want.

Correct Check

return value == null || value.isEmpty() || value.equals("null") ;

If you want to still maintain "null" as a valid username, then change whatever is sending the json to the following format, which should be interpreted as a literal null rather than a String with content "null"

"userId":null
Davis Broda
  • 4,102
  • 5
  • 23
  • 37
  • 1
    what if someone wants the userId "null"? – barbiepylon Apr 07 '15 at 19:34
  • 1
    @BarbiePylon If he has access to whatever produces the Json, the edit I added should work. If not, then he's out of luck, as there is the String `"null"` is used in place of literal `null` then there is no way to distinguish the two. – Davis Broda Apr 07 '15 at 19:40
  • 1
    I agree with you this is something OP needs to make a decision about. I just thought I'd point it out! – barbiepylon Apr 07 '15 at 19:42
4

"null" is not the same as null.

"null" is a string 4 characters in length of the word "null".

null (no quotes) is just that--nothing.

Russ
  • 4,091
  • 21
  • 32
1

{"userId":"null"} equals String userId = "null" in java.

{} would equal String userId = null when unmarshalled.

Pétur Ingi Egilsson
  • 4,368
  • 5
  • 44
  • 72