2

I have the following JSON structure

{
  "name": "xyz",
  "address": {
    "street": "avenida",
    "number": "41414-44141",
    "code": "33ll",
    "moreFields": "some data"
  },
  "moreFields": "some data"
}

In my JUNIT class I will have to compare two JSON files which have the above structure. However I would like to ignore fields address.number and address.code. I understand I can use below code to ignore one field, but how can I change this to adopt to my requirements?

assertEquals(json1, json2,
return new CustomComparator(JSONCompareMode.NON_EXTENSIBLE,
      Customization.customization("address.code",
        (o1, o2) -> {
          return true; 
        })
    ));

Looking at the implementation it appears the regex we provide to the customization method is modified and I am unable to comeup with the value for path parameter which can a OR condition.

Any suggestions are much appreciated

Thanks!

bharathp
  • 355
  • 1
  • 5
  • 16
  • You'd have to make a seperate comparator per json value you want to ignore. Either make a list of CustomComparators (if the assert allows for it) or create a DTO for your json so you have more control over the fields you want to compare – DGK Jan 25 '19 at 15:12
  • I agree with @Laurens, our team uses multiple custom comparators when it comes to testing more than one JSON field. I have not seen a better way of accomplishing this task. Duplicate: https://stackoverflow.com/questions/48429634/how-to-ignore-certain-attributes-when-comparing-two-json-files-using-skyscreamer – Brandon Jan 25 '19 at 18:33

1 Answers1

5

Try this

CustomComparator comparator = new CustomComparator(
            JSONCompareMode.LENIENT,
            new Customization("address.nunber", (o1, o2) -> true),
            new Customization("address.code", (o1, o2) -> true));
JSONAssert.assertEquals(
        expectedJsonAsString,
        actualJsonAsString,
        comparator);

I'm not quite sure regarding Xpath. Maybe you should have to try to prefix it with **. for recurve.

Take care. Julian.

Julian Kolodzey
  • 359
  • 3
  • 9