0

I know it could be a duplicate, but still posting my question as i could not find the exact answer what i am looking for. I am having an json object (or string) like below.

String str = "{
    "status" : {
        "timestamp" : "2020-04-30T01:00:00 000Z"
        "error" : 0,
        "error_message" : null,
        "execution" : "completed"
    }
}
";

I will get the a same kind of response from my REST API testing, but after each call the 'timestamp' key will be having a dynamic date and time value with the time respect to the call made. And here i compare my expect json with the actual json as a whole sting comparison using JSONAssert. As the timestamp value is different it always fails for me.

So my question is before i do any comparison, i would like to remove the 'timestamp' key and its value from json to compare and so it will pass my case. I tried by using JsonPath also, but did not works. Any help on this please?

mmar
  • 1,840
  • 6
  • 28
  • 41

1 Answers1

0

JSONAssert allow you to make a customized comparator while doing asserts [1].

In your case it's easy as:

JSONAssert.assertEquals(expectedJson,
                        actualJson,
                        new CustomComparator(JSONCompareMode.LENIENT,
                                            skips("status.timestamp","another.json.path", ...)));

private static Customization[] skips(String... jsonPaths) {
    return Arrays.stream(jsonPaths)
                 .map(jsonPath -> Customization.customization(jsonPath, (o1, o2) -> true))
                 .toArray(Customization[]::new);
}

Here we are defining CustomComparator, with customization which takes JSONPath (status.timestamp) and takes a ValueMatcher (lambda) which compares two values for that specific JSONPath.

In our case we will always return true, which will effectively skips the value (no matter with what we are comparing that value it's always true).

Edit: As you can see CustomComparator's constructor takes varargs of Customizations, hence you can provide more than one field to be ignore from comparison.


[1] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/Customization.html

[2] http://jsonassert.skyscreamer.org/apidocs/org/skyscreamer/jsonassert/comparator/CustomComparator.html

hradecek
  • 2,455
  • 2
  • 21
  • 30
  • thanks for the answer. Let me look into it. But this solution is for just skipping one key. But what if i have to skip multiple keys on the json during my comparison? sometimes, the there are other fields which i need to skip during comparison which may be in other jsonpaths. – mmar May 01 '20 at 17:16
  • There's no problem with adding more `Customization`s, see edited answer. – hradecek May 01 '20 at 17:29