tags:

views:

219

answers:

2

I'm looking for a JSON paring library that supports comparing two JSON objects ignoring child order, specifically for unit testing JSON returning from a web service against an expected value.

Do any of the major JSON libraries support this? the org.json simply does a reference comparison.

+2  A: 

I'd take the library at http://json.org/java/, and modify the equals method of JSONObject and JSONArray to do a deep equality test. To make sure that it works regradless of the order of the children, all you need to do is replace the inner map with a TreeMap, or use something like Collections.sort().

Yoni
I have used this library - it works well.
GreenieMeanie
+2  A: 

As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.

Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:

public boolean equals(Object o)
{
    if (o == this) return true;
    if (o == null) return false;
    if (o.getClass() != getClass()) {
        return false;
    }
    ObjectNode other = (ObjectNode) o;
    if (other.size() != size()) {
        return false;
    }
    if (_children != null) {
        for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
            String key = en.getKey();
            JsonNode value = en.getValue();

            JsonNode otherValue = other.get(key);

            if (otherValue == null || !otherValue.equals(value)) {
                return false;
            }
        }
    }
    return true;
}
Jolly Roger
This method is not symmetric, as it only tests 'subset' relationship of the children, not equality. the 'other' object may have more children then in _children, and this method would still return true.
Yoni
@Yoni: Not true, as there's a size comparison. They must have the exact same number of children as well as the same children.@Jolly Roger: In this case, I'm not serializing the object from JSON back into a POJO, but when sending JSON a system that does, I can't rely on it sending it back in the exact same format in which I sent it.
Jeff
@Jeff, you're right, I missed that
Yoni