Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-08 09:40:02
Original
782 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!