anuni
anuni

Reputation: 999

How to compare 2 json by ignoring some attributes and child element orders

I'm seeking for a java library which can give fine grain control on json comparision. (just like XMLUnit)

For example, I have below 2 json document:

Control:

{
   "timestamp":1234567,
   "items":[
      {
         "id":111,
         "title":"Test Item 111"
      },
      {
         "id":222,
         "title":"Test Item 222"
      }
   ]
}

Test:

{
   "timestamp":7654321,
   "items":[
      {
         "id":222,
         "title":"Test Item 222"
      },
      {
         "id":111,
         "title":"Test Item 111"
      },
      {
         "id":333,
         "title":"Test Item 333"
      }
   ]
}

I'd like to apply below semantics when comparing them:

Any suggestions?

Upvotes: 2

Views: 900

Answers (2)

anuni
anuni

Reputation: 999

JsonUnit seems to help:

https://github.com/lukas-krecan/JsonUnit#options

for my case:

Configuration cfg = Configuration.empty().when(path("items"), then(Option.IGNORING_ARRAY_ORDER, Option.IGNORING_EXTRA_ARRAY_ITEMS)).when(path("timestamp"), thenIgnore());

Diff diff = Diff.create(control, test, "", "", cfg);
assertTrue(diff.similar());

Upvotes: 1

JPBorges
JPBorges

Reputation: 53

As point out in your tags you can use Jackson to convert the both json to a Java class.

You can override the equals method within the class with your desired condition.

After all just use equals function in your objects.

Upvotes: 1

Related Questions