Orlangure Orlangure - 8 months ago 25
JSON Question

Does org.json.JSONObject breaks Object.equals() contract?

In JSONObject.NULL documentation example there is the following line:

JSONObject.NULL.equals(null); //returns true

It breaks
contract, at least it seems like it does, since

For any non-null reference value x, x.equals(null) should return false

The fact that this class is so widely used and supported makes me think that there is no violation for some reason, is there?

sJy sJy

It clearly violates the Object.equals() since

  • JSONObject.NULL is not null but a new Object()
  • Return value is true instead of false

JSONObject.NULL from source looks like below & the value is not null.

public static final Object NULL = new Object() {

    @Override public boolean equals(Object o) {
        return o == this || o == null; // API specifies this broken equals implementation

    @Override public String toString() {
        return "null";


equals() from Object looks like

public boolean equals(Object o) {
    return this == o;

The additional comparison of o == null in JSONObject.NULL equals() method will always return true if we pass null. Hence

JSONObject.NULL.equals(null); //Will return true