Home  >  Article  >  Java  >  How to Test JSON Object Equality Ignoring Child Order in Java?

How to Test JSON Object Equality Ignoring Child Order in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 01:17:02361browse

How to Test JSON Object Equality Ignoring Child Order in Java?

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:

  • Object extensibility: Allows additional fields in the actual JSON object that are not present in the expected JSON object.
  • Loose array ordering: Considers arrays with different element orders as equal.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn