"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Compare JSON Objects for Equality While Ignoring Child Order in Java?

How to Compare JSON Objects for Equality While Ignoring Child Order in Java?

Published on 2024-11-20
Browse:522

How to Compare JSON Objects for Equality While Ignoring Child Order in Java?

Testing JSON Objects for Equality while Ignoring Child Order in Java

In unit testing, it is common to compare JSON objects returned from web services to expected values. However, some JSON libraries might perform strict reference comparisons, which can be brittle and fail due to differences in child order.

For this purpose, the Skyscreamer JSONAssert library provides a solution. Its non-strict mode allows for flexibility by:

  • Permitting object extensibility: Expected objects can include additional fields without causing the comparison to fail.
  • Allowing loose array ordering: Arrays can be out of order and still pass the comparison.

In contrast, strict mode behaves more conservatively, similar to json-lib's test class.

To utilize JSONAssert, tests can be constructed as follows:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
          ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false); // Non-strict mode
}

The parameters in JSONAssert.assertEquals() include the expected JSON string, actual data string, and a flag indicating strict mode or not.

JSONAssert provides clear error messages, which is crucial when comparing large JSON objects, ensuring robustness in unit testing.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3