Testing JSON Object Equality Ignoring Child Order in Java
When unit testing JSON responses from web services, it's crucial to compare the results for equality. However, the order of child elements within the JSON objects should not affect the comparison. To address this challenge, let's explore a suitable JSON parsing library.
Solution: Skyscreamer's JSONAssert
Skyscreamer's JSONAssert offers a non-strict mode that accommodates two key requirements:
Test Example
<code class="java">@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); }</code>
In this example, the expected JSON object specifies an array of friends with IDs 123 and 456. The actual JSON object might have additional fields or a different order of elements in the array. JSONAssert will still consider them equal in non-strict mode.
The above is the detailed content of How to Test JSON Object Equality Ignoring Child Order in Java?. For more information, please follow other related articles on the PHP Chinese website!