2

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:

  • Ignore 'timestamp'
  • When comparing 'items', please do head to head compare against 'id'

Any suggestions?

anuni
  • 889
  • 10
  • 26
  • You can try [zjsonpatch](https://github.com/flipkart-incubator/zjsonpatch) – Smile Jun 09 '20 at 07:37
  • Does this answer your question? [Testing two JSON objects for equality ignoring child order in Java](https://stackoverflow.com/questions/2253750/testing-two-json-objects-for-equality-ignoring-child-order-in-java) – Smile Jun 09 '20 at 08:44
  • I've checked this one. It seems doe not include my first requirement "ignore some element". – anuni Jun 09 '20 at 08:50

2 Answers2

1

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.

JPBorges
  • 53
  • 5
  • I may have dundreds of such json documents which serves for different biz purpose, and I don't know the mapping java classes for each case. – anuni Jun 09 '20 at 08:43
1

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());
anuni
  • 889
  • 10
  • 26