Ignore a specific node while performing equal check on two complex JSON objects

40 views Asked by At

I have a unit test that compares two complex JSONObjects. I want to compare the whole of both of the objects but I want to ignore just one specific field (ie. timestamp. something which is always variable). Here is my code :

JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
JSONObject jsonObject1 = (JSONObject) parser.parse(expectedErrorMessage);
JSONObject jsonObject2 = (JSONObject) parser.parse(lastMessage.toString());

Assertions.assertEquals(jsonObject1, jsonObject2);

I was initially thinking the best way is to set a value in the JSONTree to null or some kind of arbitrary value. So the idea is some method that might look like this (like in javascript immutable library):

jsonObject = updateAJsonField(jsonObject, ["path","to", "field"], newValue)

Otherwise there is using a comparator in the equals, but it seems more trouble than its worth.

(ps i am using net.minidev.json)

Any ideas how to ignore a field deep in a complex JSON object?

1

There are 1 answers

0
Oliver Watkins On

Unfortunately I could not find anything on the internet that solved my problem, so I created my own Method which replaces a JSON value (using org.json.JSONObject) with a particular value.

public static String replaceJSONValueAtPath(String jsonString, String[] pathToValue, Object value) throws JSONException {

    JSONObject obj = new org.json.JSONObject(new JSONTokener(jsonString));

    JSONObject current = obj;
    // Traverse the JSON tree along the path specified
    for (int i = 0; i < pathToValue.length - 1; i++) {
        current = current.getJSONObject(pathToValue[i]);
    }

    // Replace the value at the specified path
    current.put(pathToValue[pathToValue.length - 1], value);
    return obj.toString();
}

Here is the test :

@Test
public void test() throws JSONException {
    String stringIn = "{'a': {'b' : {'c': 'oldValue'} }}";
    String stringOut = TestUtils.replaceJSONValueAtPath(stringIn, new String[]{"a", "b", "c"}, "newValue");
    String sTest = "{\"a\":{\"b\":{\"c\":\"newValue\"}}}";
    Assertions.assertEquals(sTest, stringOut);
}