Skip to content

Instantly share code, notes, and snippets.

@iperdomo
Created June 4, 2012 11:58
Show Gist options
  • Save iperdomo/2867928 to your computer and use it in GitHub Desktop.
Save iperdomo/2867928 to your computer and use it in GitHub Desktop.
Handling null values (JSONObject)
package org.openbravo.test;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* @author iperdomo
*/
public class NullTest {
public static void main(String[] args) throws JSONException {
// https://fisheye.codehaus.org/browse/jettison/trunk/src/main/java/org/codehaus/jettison/json/JSONObject.java?r=104
JSONObject test = new JSONObject("{ \"address\": null}");
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is
* equivalent to the value that JavaScript calls undefined.
*/
// false
System.out.println(test.get("address") == null);
System.out.println(test.getString("address").equals(null));
/**
*
* It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's
* null value.
*
* JSONObject.NULL.equals(null) returns true.
*
* JSONObject.NULL.toString() returns "null".
*/
// true
System.out.println(test.get("address").equals(null)); // Preferred way
System.out.println(test.getString("address").equals("null"));
try {
System.out.println(test.get("nonexistent") == null);
System.out.println(test.getString("nonexistent").equals("null"));
} catch (Exception e) {
System.err.println(e);
}
}
}
@iperdomo
Copy link
Author

The result is:

false
false
true
true
org.codehaus.jettison.json.JSONException: JSONObject["nonexistent"] not found.

@kaecy
Copy link

kaecy commented Sep 19, 2017

Thanks. This helped.

@teguhteja
Copy link

this works !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment