Home >Java >javaTutorial >How to Compare JSON Objects without Regarding Child Order in Java?

How to Compare JSON Objects without Regarding Child Order in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 09:40:02991browse

How to Compare JSON Objects without Regarding Child Order in Java?

Comparing JSON Objects in Java without Regard to Child Order

When unit testing JSON responses from web services, parsing libraries that compare JSON objects while disregarding child order can be invaluable.

Solution: Skyscreamer's JSONAssert

Skyscreamer's JSONAssert library provides a solution. Its "non-strict" mode allows:

  • Object extensibility: Expected value {id:1} matches {id:1,moredata:'x'}.
  • Loose array ordering: ['dog','cat'] equals ['cat','dog'].

In strict mode, JSONAssert functions similarly to json-lib's test class.

Example Usage

<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); // "false" for non-strict mode
}</code>

Additional Features

  • Clear error messages when comparing large JSON objects
  • Provides both non-strict and strict comparison modes

The above is the detailed content of How to Compare JSON Objects without Regarding 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