elemental.json
.
*
* @author Vaadin Ltd
*/
public class JsonUtil {
/**
* Collects a stream of JSON values to a JSON array.
*/
private static final class JsonArrayCollector
implements Collector
* This is a helper for overcoming the fact that {@link JsonValue} doesn't
* override {@link Object#equals(Object)} and
* {@link JsonValue#jsEquals(JsonValue)} is defined to use JavaScript
* semantics where arrays and objects are equals only based on identity.
*
* @param a
* the first JSON value to check, may not be null
* @param b
* the second JSON value to check, may not be null
* @return true
if both JSON values are the same;
* false
otherwise
*/
public static boolean jsonEquals(JsonValue a, JsonValue b) {
assert a != null;
assert b != null;
if (a == b) {
return true;
}
JsonType type = a.getType();
if (type != b.getType()) {
return false;
}
switch (type) {
case NULL:
return true;
case BOOLEAN:
return a.asBoolean() == b.asBoolean();
case NUMBER:
return Double.doubleToRawLongBits(a.asNumber()) == Double
.doubleToRawLongBits(b.asNumber());
case STRING:
return a.asString().equals(b.asString());
case OBJECT:
return jsonObjectEquals((JsonObject) a, (JsonObject) b);
case ARRAY:
return jsonArrayEquals((JsonArray) a, (JsonArray) b);
default:
throw new IllegalArgumentException("Unsupported JsonType: " + type);
}
}
private static boolean jsonObjectEquals(JsonObject a, JsonObject b) {
assert a != null;
assert b != null;
if (a == b) {
return true;
}
String[] keys = a.keys();
if (keys.length != b.keys().length) {
return false;
}
for (String key : keys) {
JsonValue value = b.get(key);
if (value == null || !jsonEquals(a.get(key), value)) {
return false;
}
}
return true;
}
private static boolean jsonArrayEquals(JsonArray a, JsonArray b) {
assert a != null;
assert b != null;
if (a == b) {
return true;
}
if (a.length() != b.length()) {
return false;
}
for (int i = 0; i < a.length(); i++) {
if (!jsonEquals(a.get(i), b.get(i))) {
return false;
}
}
return true;
}
/**
* Creates a stream from a JSON array.
*
* @param array
* the JSON array to create a stream from
* @return a stream of JSON values
*/
public static