13

I'm trying to parse some JSON in Grails using the grails.converters.JSON library. I have a field which will contain either a string, or a null value. When I parse the JSON and get the field, the null values come back as a JSONObject.NULL type. This is not good when checking != null as JSONObject.NULL is evaluated as non-null (not good for null checks)

def obj = JSON.parse('{"date1":null,"date2":"2011-06-26T05:00:00Z"}')
def date1 = obj.date1
if (date1)
     parse(date1)   // parse error occurs here because date1 evaluates true in the if because it is JSONObject.NULL

Is there an easy way to get the parse to parse a real null value so that I don't have to check if the object is a JSONObject.NULL.

I tried the suggestion here to use .toString(), but it ended up returning the string value 'null' instead of actual null for a JSONObject.NULL value.

Scott
  • 16,711
  • 14
  • 75
  • 120
  • there is the closing quote missing for the date string. is this maybe the issue? – Chris Oct 22 '11 at 18:35
  • this is example code for illustration, not actual running code. it's for illustration. I've corrected the quote, but that's not the problem I'm illustrating – Scott Oct 23 '11 at 17:25

3 Answers3

19

You may find this more useful and natural

    JSONObject.NULL.equals(jsonObj.get("key_name"))
Hado99
  • 555
  • 6
  • 15
  • I am getting `NullPointerException` when I use `JSONObject.NULL.equals(...)`. In the debugger I see that `JSONObject.NULL = null`.... – nrofis Jan 02 '17 at 14:36
  • Depending on the library you are using, please see http://docs.oracle.com/javaee/7/api/javax/json/JsonValue.html#NULL https://developer.android.com/reference/org/json/JSONObject.html#NULL – Hado99 Jan 03 '17 at 18:13
13

Have a look at: http://grails.1312388.n4.nabble.com/The-groovy-truth-of-JSONObject-Null-td3661040.html

Ian Roberts mentions a nice trick to make a null check possible:

JSONObject.NULL.metaClass.asBoolean = {-> false} 
Chris
  • 8,031
  • 10
  • 41
  • 67
  • Note that this still does not allow you to use the safe navigation operator `?.` as would be natural with a "real" map. – Desty Oct 23 '15 at 11:19
-2

I think I found a better solution, which consists in overriding the toString() method implementation of the JSONObject.NULL inner class by copying the JSONObject.java file into your Grails src/java project and then changing the implementation to this:

    /**
     * Get the "" string value.
     * @return An empty String "".
     */
    @Override
    public String toString() {
        return "";
    }

Once you restart with this new class in your classpath, the classloader will use your JSONObject class instead of the one packaged in the Grails dependencies.

Make sure you keep it in the same package as the original.

For more details you can go here: https://github.com/grails/grails-core/issues/9129

Hope it helps :-)

aruizca
  • 1,891
  • 1
  • 19
  • 13