JSONObject.similar(JSONObject) what does this really compare?

Here's the source for JSONObject.similar():

/**
 * Determine if two JSONObjects are similar.
 * They must contain the same set of names which must be associated with
 * similar values.
 *
 * @param other The other JSONObject
 * @return true if they are equal
 */
public boolean similar(Object other) {
    try {
        if (!(other instanceof JSONObject)) {
            return false;
        }
        Set<String> set = this.keySet();
        if (!set.equals(((JSONObject)other).keySet())) {
            return false;
        }
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String name = iterator.next();
            Object valueThis = this.get(name);
            Object valueOther = ((JSONObject)other).get(name);
            if (valueThis instanceof JSONObject) {
                if (!((JSONObject)valueThis).similar(valueOther)) {
                    return false;
                }
            } else if (valueThis instanceof JSONArray) {
                if (!((JSONArray)valueThis).similar(valueOther)) {
                    return false;
                }
            } else if (!valueThis.equals(valueOther)) {
                return false;
            }
        }
        return true;
    } catch (Throwable exception) {
        return false;
    }
}

Essentially similar() recursively compares the names and values of the JSONObjects and returns true if they're the same. First, it checks if the keysets are equal, then moves on to the values. It recursively checks each value in the keyset to see if they are equal in each JSONObject. If not, it returns false.


The description you found relates to method JSONObject.similar(), which compares if two JSON objects are the same, but having perhaps a different order of its attributes.

The equals() will compare each string caracter, one-by-one checking if it is the same, having the same order.

Tags:

Java

Json