• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to parse "null" string to null.  RSS feed

 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is there a method that will parse
- given string "null" to null,
- will leave other string values untouched,
- and given value null will also remain null.

Basically a more readable equivalent of:
I noticed String.valueOf(Object o) returns "null" explicitly when given object o is null, so I guess there should be a method that does the opposite, parsing "null" to null.

Cheers,
Kjeld
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried what you wrote? Try changing equals to equalsIgnoreCase, so you can pass "null" "Null" or "NULL". Otherwise it looks perfectly good to me. You are lacking a semicolon and you have an unmatched ) right round bracket/parenthesis.

Why do you want to introduce nulls into your application in the first place? It is usually better to get avoid nulls.
 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks, I was a little quick in posting the code, I have changed it so it will compile.
Yes this is the code I currently use. I am convinced I have seen some method once, that does the same thing. Perhaps it was in the Apache commons library.

We allow users of our custom logging application to provide a "null" string in a property file, to express they actually mean null (no value). Therefore in this case I need the solution to be case sensitive (only allows lower case "null").
Another situation I can think of (which is not the case here) is a web application where a client HTML input value "null" is expected to evaluate to null. E.g. because unintentionally string "null" was put in the HTML input field value by default (because the form field value is null), and you do not want the request action to change the form value to string "null" just because the HTML input literally was "null". You will want a validator to notice invalid value null for a last name, where "null" would be accepted as a valid last name...
A third example is when you explicitly do not want your application to store the string "null" in a database's nullable (var)char field. An SQL query that says WHERE ... IS NULL would leave out these results.

Thanks!
Kjeld
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sounds a reasonable explanation; as I said earlier, that code looks good to me
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!