Java Code Examples for com.google.gson.JsonElement#equals()

The following examples show how to use com.google.gson.JsonElement#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RESTUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
/**
* 
* @Title      : diff 
* @Description: Differ JSON nodes 
* @Param      : @param json1
* @Param      : @param json2
* @Param      : @param excludedNodes
* @Param      : @return 
* @Return     : boolean
* @Throws     :
 */
public static boolean diff(String json1, String json2, List<String> exclNodes)
{
    if (CollectionUtils.isEmpty(exclNodes))
    {
        return json1.equals(json2);
    }

    JsonParser p = new JsonParser();
    JsonElement e1 = p.parse(json1);
    JsonElement e2 = p.parse(json2);

    jsonTree(e1, "", exclNodes);
    jsonTree(e2, "", exclNodes);

    return e1.equals(e2);
}
 
Example 2
Source File: RESTUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
/**
* 
* @Title: compare 
* @Description: Compare two json text 
* @param @param jtxt1
* @param @param jtxt2
* @param @return     
* @return boolean    
* @throws
 */
public static boolean compare(String jstr1, String jstr2)
{
    JsonParser p = new JsonParser();
    JsonElement e1 = p.parse(jstr1);
    JsonElement e2 = p.parse(jstr2);

    sort(e1);
    sort(e2);

    return e1.equals(e2);
}
 
Example 3
Source File: ApiSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сравниваются с ожидаемым значением во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^в json (?:строке|файле) \"([^\"]*)\" значения, найденные по jsonpath, равны значениям из таблицы$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" found via jsonpath are equal to the values from the table$")
public void checkValuesInJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    JsonParser parser = new JsonParser();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        JsonElement actualJsonElement;
        try {
            actualJsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        JsonElement expectedJsonElement = parser.parse(row.get(1));
        if (!actualJsonElement.equals(expectedJsonElement)) {
            error = true;
        }
        akitaScenario.write("JsonPath: " + jsonPath + ", ожидаемое значение: " + expectedJsonElement + ", фактическое значение: " + actualJsonElement);
    }
    if (error)
        throw new RuntimeException("Ожидаемые и фактические значения в json не совпадают");
}
 
Example 4
Source File: JsonObjectMatcher.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
private boolean equalToAnyOther(JsonElement thisItem, JsonArray otherArray) {
    for (int i = 0; i < otherArray.size(); i++) {
        JsonElement otherItem = otherArray.get(i);
        if (thisItem.isJsonObject()) {
            if (!otherItem.isJsonObject())
                continue;
            if (new JsonObjectMatcher(thisItem.getAsJsonObject()).matchesSafely(otherItem.getAsJsonObject()))
                return true;
        } else if (thisItem.equals(otherItem))
            return true;
    }
    return false;
}
 
Example 5
Source File: OptimizelyTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
private boolean compareJsonStrings(String str1, String str2) {
    JsonParser parser = new JsonParser();

    JsonElement j1 = parser.parse(str1);
    JsonElement j2 = parser.parse(str2);
    return j1.equals(j2);
}
 
Example 6
Source File: SpotifyServiceAndroidTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Override
public boolean matches(Object actualRaw) {
    JsonElement actualJsonElement = sGson.toJsonTree(actualRaw);
    String withoutNulls = sGson.toJson(mExpectedJsonElement);
    JsonElement expectedJsonElementWithoutNulls = sGson.fromJson(withoutNulls, JsonElement.class);
    return expectedJsonElementWithoutNulls.equals(actualJsonElement);
}
 
Example 7
Source File: Util.java    From azure-mobile-apps-android-client with Apache License 2.0 4 votes vote down vote up
public static boolean compareJson(JsonElement e1, JsonElement e2) {
    // NOTE: if every property defined in e1 is in e2, the objects are
    // considered equal.

    if (e1 == null && e2 == null) {
        return true;
    }

    if (e1 == null || e2 == null) {
        return false;
    }

    if (e1.getClass() != e2.getClass()) {
        return false;
    }

    if (e1 instanceof JsonPrimitive) {
        JsonPrimitive p1 = (JsonPrimitive) e1;
        JsonPrimitive p2 = (JsonPrimitive) e2;

        if (p1.isString()) {
            try {
                Date d1 = DateSerializer.deserialize(p1.getAsString());
                Date d2 = DateSerializer.deserialize(p2.getAsString());

                if (!d1.equals(d2) && !e1.equals(e2)) {
                    return false;
                }
            } catch (Throwable t) {
                if (!e1.equals(e2)) {
                    return false;
                }
            }
        } else if (!e1.equals(e2)) {
            return false;
        }
    } else if (e1 instanceof JsonArray) {
        JsonArray a1 = (JsonArray) e1;
        JsonArray a2 = (JsonArray) e2;

        if (a1.size() != a2.size()) {
            return false;
        }

        for (int i = 0; i < a1.size(); i++) {
            if (!compareJson(a1.get(i), a2.get(i))) {
                return false;
            }
        }
    } else if (e1 instanceof JsonObject) {
        JsonObject o1 = (JsonObject) e1;
        JsonObject o2 = (JsonObject) e2;

        Set<Entry<String, JsonElement>> entrySet1 = o1.entrySet();

        for (Entry<String, JsonElement> entry : entrySet1) {

            if (entry.getKey().toLowerCase(Locale.getDefault()).equals("id")) {
                continue;
            }

            String propertyName1 = entry.getKey();
            String propertyName2 = null;
            for (Entry<String, JsonElement> entry2 : o2.entrySet()) {

                if (propertyName1.toLowerCase(Locale.getDefault()).equals(entry2.getKey().toLowerCase(Locale.getDefault()))) {
                    propertyName2 = entry2.getKey();
                }
            }

            if (propertyName2 == null) {
                return false;
            }

            if (!compareJson(entry.getValue(), o2.get(propertyName2))) {
                return false;
            }
        }
    }

    return true;
}
 
Example 8
Source File: JsonStructureChecker.java    From MOE with Apache License 2.0 4 votes vote down vote up
private void requireSimilarNoKey(JsonElement a, JsonElement b) {
  if (a.getClass() == b.getClass()) {
    if (a instanceof JsonArray) {
      Iterator<JsonElement> aEls = ((JsonArray) a).iterator();
      Iterator<JsonElement> bEls = ((JsonArray) b).iterator();
      int index = 0;
      for (; aEls.hasNext() && bEls.hasNext(); ++index) {
        requireSimilar(index, aEls.next(), bEls.next());
      }
      if (aEls.hasNext() || bEls.hasNext()) {
        addKey(index);
        dissimilar();
      }
      return;
    } else if (a instanceof JsonObject) {
      Iterator<Map.Entry<String, JsonElement>> aProps = ((JsonObject) a).entrySet().iterator();
      Iterator<Map.Entry<String, JsonElement>> bProps = ((JsonObject) b).entrySet().iterator();
      // We don't ignore order of properties.
      while (aProps.hasNext() && bProps.hasNext()) {
        Map.Entry<String, JsonElement> aEntry = aProps.next();
        Map.Entry<String, JsonElement> bEntry = bProps.next();
        String aKey = aEntry.getKey();
        if (aKey.equals(bEntry.getKey())) {
          requireSimilar(aKey, aEntry.getValue(), bEntry.getValue());
        } else {
          addKey(aKey);
          dissimilar();
        }
      }
      if (aProps.hasNext()) {
        addKey(aProps.next().getKey());
        dissimilar();
      } else if (bProps.hasNext()) {
        addKey(bProps.next().getKey());
        dissimilar();
      }
      return;
    } else if (a instanceof JsonPrimitive) {
      // Ignore all number differences.  There are a number of
      // kinds of differences we want to ignore.
      // 1. (1I, 1L, 1D) are similar enough.
      // 2. (-0, +0)
      // 3. Small differences in decimal decoding.
      if (((JsonPrimitive) a).isNumber()
          && ((JsonPrimitive) b).isNumber()) {
        return;
      }
    }
  }
  if (!a.equals(b)) {
    dissimilar();
  }
}
 
Example 9
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 3 votes vote down vote up
/**
 * Compares two JSON strings if they contain the same data even if the order
 * of the keys differs.
 *
 * @param expected The JSON to test against
 * @param actual   The tested JSON
 * @return true if JSONs contain the same data, false otherwise.
 */
private boolean JSONsContainSameData(String expected, String actual) {
    JsonParser parser = new JsonParser();
    JsonElement expectedJsonElement = parser.parse(expected);
    JsonElement actualJsonElement = parser.parse(actual);

    return expectedJsonElement.equals(actualJsonElement);
}