### Add JSONAssert Maven Dependency Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/quickstart.html Include the JSONAssert library in your project by adding this dependency to your pom.xml file. ```xml org.skyscreamer jsonassert 2.0-rc1 ``` -------------------------------- ### Perform JSON Assertion in JUnit Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/quickstart.html Use JSONAssert.assertEquals to compare an expected JSON string against an actual result. The strictMode parameter allows toggling between strict field/order enforcement and flexible matching. ```java @Test public void testGetUser() { Assert.assertTrue(_restService.isEnabled()); String result = _restService.get("/user/123.json"); JSONAssert.assertEquals("{id:123,name:\"Joe\"}", result, false); } ``` -------------------------------- ### Implement Custom Field Matching with CustomComparator Source: https://context7.com/skyscreamer/jsonassert/llms.txt Demonstrates how to use CustomComparator to override default equality checks. Includes examples for ignoring fields, regex validation, wildcard path matching, and custom range logic. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonassert.ValueMatcher; import org.skyscreamer.jsonassert.RegularExpressionValueMatcher; import org.skyscreamer.jsonassert.comparator.CustomComparator; // Ignore a specific field during comparison String expected = "{id:1,timestamp:\"any\"}"; String actual = "{id:1,timestamp:\"2024-01-15T10:30:00Z\"}"; Customization ignoreTimestamp = new Customization("timestamp", (o1, o2) -> true); JSONAssert.assertEquals(expected, actual, new CustomComparator(JSONCompareMode.STRICT, ignoreTimestamp)); // Use regex to validate field format String expectedWithPattern = "{id:\"X\",email:\"X\"}"; String actualData = "{id:\"12345\",email:\"user@example.com\"}"; CustomComparator regexComparator = new CustomComparator( JSONCompareMode.STRICT, new Customization("id", new RegularExpressionValueMatcher<>("\\d+")), new Customization("email", new RegularExpressionValueMatcher<>("[\\w.]+@[\\w.]+")) ); JSONAssert.assertEquals(expectedWithPattern, actualData, regexComparator); // Wildcard path matching with **. (matches any prefix) String nestedExpected = "{users:[{id:1,created:\"X\"},{id:2,created:\"X\"}]}"; String nestedActual = "{users:[{id:1,created:\"2024-01-01\"},{id:2,created:\"2024-01-02\"}]}"; CustomComparator wildcardComparator = new CustomComparator( JSONCompareMode.STRICT, new Customization("**.created", (o1, o2) -> true) ); JSONAssert.assertEquals(nestedExpected, nestedActual, wildcardComparator); // Single wildcard * matches single path segment String patternExpected = "{data:{user1:{score:0},user2:{score:0}}}"; String patternActual = "{data:{user1:{score:85},user2:{score:92}}}"; CustomComparator singleWildcard = new CustomComparator( JSONCompareMode.STRICT, new Customization("data.*.score", (o1, o2) -> ((Number)o2).intValue() >= 0) ); JSONAssert.assertEquals(patternExpected, patternActual, singleWildcard); // Custom ValueMatcher implementation ValueMatcher rangeChecker = (expected1, actual1) -> { int value = ((Number) actual1).intValue(); return value >= 0 && value <= 100; }; CustomComparator customMatcher = new CustomComparator( JSONCompareMode.LENIENT, new Customization("score", rangeChecker) ); JSONAssert.assertEquals("{score:0}", "{score:75}", customMatcher); ``` -------------------------------- ### JSONassert Example: Comparing JSON Strings with JUnit Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/index.html Demonstrates how to use JSONAssert.assertEquals to compare an expected JSON string with actual JSON data retrieved from a REST interface. The 'strict' parameter set to false allows for flexible comparisons, ignoring data reordering and extra fields. ```java import org.json.JSONObject; import org.skyscreamer.jsonassert.JSONAssert; // ... inside a test method ... JSONObject data = getRESTData("/friends/367.json"); String expected = "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}"; JSONAssert.assertEquals(expected, data, false); ``` -------------------------------- ### Nested JSON Structures Assertion in Java Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/cookbook.html This example demonstrates how to use JSONAssert to test complex, nested JSON structures, including arrays of arrays and arrays of objects. The strictness rules for objects and arrays apply recursively at all levels of nesting. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.junit.jupiter.api.Test; public class NestedJsonAssertExamples { @Test public void testNestedArrayOfArrays() { String result = "{id:1,stuff:[[1,2],[2,3],[],[3,4]]}"; // Testing nested arrays with strict order JSONAssert.assertEquals("{id:1,stuff:[[1,2],[2,3],[],[3,4]]}", result, true); // Pass } @Test public void testNestedArrayOfArraysLooseOrder() { String result = "{id:1,stuff:[[1,2],[2,3],[],[3,4]]}"; // Testing nested arrays with loose order JSONAssert.assertEquals("{id:1,stuff:[[4,3],[3,2],[],[1,2]]}", result, false); // Pass } @Test public void testComplexNestedStructure() { String result = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}"; // Asserting a complex structure with nested objects and arrays, strict order JSONAssert.assertEquals("{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}", result, true); // Pass } @Test public void testComplexNestedStructureLooseOrder() { String result = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}"; // Asserting a complex structure with nested objects and arrays, loose order for arrays and objects JSONAssert.assertEquals("{name:\"Joe\",friends:[{id:3,name:\"Sue\",pets:[\"fish\",\"bird\"]},{id:2,name:\"Pat\",pets:[\"dog\"]}],pets:[],id:1}", result, false); // Pass } @Test public void testDeeplyNestedObject() { String result = "{a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{k:{l:{m:{n:{o:{p:\"blah\"}}}}}}}}}}}}}}}"; // Asserting a deeply nested JSON object JSONAssert.assertEquals("{a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{k:{l:{m:{n:{o:{p:\"blah\"}}}}}}}}}}}}}}}", result, true); // Pass } } ``` -------------------------------- ### JSONassert Example: Detailed JSON Comparison Error Message Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/index.html Illustrates a scenario where JSONAssert.assertEquals is used with 'strict' set to false, and the actual JSON differs from the expected JSON. The output shows a detailed error message pinpointing the discrepancy in the 'pets' array for a friend with id=3. ```java String expected = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}] ,pets:[]}"; String actual = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"cat\",\"fish\"]}] ,pets:[]}"; JSONAssert.assertEquals(expected, actual, false); ``` -------------------------------- ### JSON Array Assertion in Java Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/cookbook.html This example shows how to assert JSON arrays using JSONAssert. It covers scenarios where the order of elements is important (strict mode) and where it is not. Unlike JSON objects, array elements must always match, and arrays cannot be 'extended' with extra elements. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.junit.jupiter.api.Test; public class JsonArrayAssertExamples { @Test public void testOrderedArrayStrict() { String result = "[1,2,3,4,5]"; // Strict mode enabled, order is important JSONAssert.assertEquals("[1,2,3,4,5]", result, true); // Pass } @Test public void testUnorderedArrayStrictFail() { String result = "[1,2,3,4,5]"; // Strict mode enabled, different order fails try { JSONAssert.assertEquals("[5,3,2,1,4]", result, true); // Fail } catch (AssertionError e) { System.out.println("Assertion failed as expected: " + e.getMessage()); } } @Test public void testUnorderedArrayLoose() { String result = "[1,2,3,4,5]"; // Strict mode disabled, order does not matter JSONAssert.assertEquals("[5,3,2,1,4]", result, false); // Pass } @Test public void testArrayMustMatchExactly() { String result = "[1,2,3,4,5]"; // Arrays must match exactly, cannot be extended JSONAssert.assertEquals("[1,2,3,4,5]", result, false); // Pass } @Test public void testArrayExtensionFail() { String result = "[1,2,3,4,5]"; // Attempting to extend an array fails try { JSONAssert.assertEquals("[1,2,3,4,5,6]", result, false); // Fail } catch (AssertionError e) { System.out.println("Assertion failed as expected: " + e.getMessage()); } } @Test public void testArrayShorterFail() { String result = "[1,2,3,4,5]"; // Attempting to assert a shorter array fails try { JSONAssert.assertEquals("[1,2,3]", result, false); // Fail } catch (AssertionError e) { System.out.println("Assertion failed as expected: " + e.getMessage()); } } } ``` -------------------------------- ### Simple JSON Object Assertion in Java Source: https://github.com/skyscreamer/jsonassert/blob/master/src/site/resources/cookbook.html This example demonstrates a basic assertion for a JSON object using JSONAssert. It takes a JSON string as input and compares it against an expected JSON structure. The `strictMode` is set to false, meaning field order does not matter and extra fields in the result are ignored. ```java import org.json.JSONObject; import org.skyscreamer.jsonassert.JSONAssert; import org.junit.jupiter.api.Test; public class JsonAssertExamples { // Assume getJSONResult() is a method that returns a JSON string private String getJSONResult(String endpoint) { // Placeholder for actual JSON retrieval logic if ("/user/1.json".equals(endpoint)) { return "{id:1, name:\"John Doe\"}"; } return "{}"; } @Test public void testSimpleJsonObject() { String result = getJSONResult("/user/1.json"); // Simple assertion, strictMode is false by default JSONAssert.assertEquals("{id:1}", result, false); } @Test public void testJsonObjectWithExtraFields() { String result = "{id:1, name:\"Juergen\"}"; // With strictMode false, extra fields are ignored JSONAssert.assertEquals("{id:1}", result, false); // Pass } @Test public void testJsonObjectWithExtraFieldsStrict() { String result = "{id:1, name:\"Juergen\"}"; // With strictMode true, extra fields cause a failure try { JSONAssert.assertEquals("{id:1}", result, true); // Fail } catch (AssertionError e) { System.out.println("Assertion failed as expected: " + e.getMessage()); } } @Test public void testJsonObjectFieldOrderDoesNotMatter() { String result = "{id:1, name:\"Juergen\"}"; // Field order does not matter when strictMode is true or false JSONAssert.assertEquals("{name:\"Juergen\",id:1}", result, true); // Pass } } ``` -------------------------------- ### JSON Comparison and Error Reporting in Java Source: https://context7.com/skyscreamer/jsonassert/llms.txt Demonstrates how to use JSONassert in Java to compare JSON strings and retrieve detailed error messages. It covers scenarios like field value mismatches, missing fields, type mismatches, and array length differences. This requires the jsonassert library as a dependency. ```java import org.skyscreamer.jsonassert.JSONCompare; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.JSONCompareResult; // Field value mismatch - shows path and values String expected = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}]}"; String actual = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"cat\",\"fish\"]}]}"; JSONCompareResult result = JSONCompare.compareJSON(expected, actual, JSONCompareMode.LENIENT); System.out.println(result.getMessage()); // Output: friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected // Missing field detection String missingField = "{id:1}"; String withExtraField = "{id:1,name:\"Joe\"}"; result = JSONCompare.compareJSON(withExtraField, missingField, JSONCompareMode.STRICT); System.out.println(result.getMessage()); // Output shows: name - Expected name but not found // Type mismatch String typeExpected = "{value:\"123\"}"; String typeActual = "{value:123}"; result = JSONCompare.compareJSON(typeExpected, typeActual, JSONCompareMode.STRICT); if (result.failed()) { System.out.println("Type mismatch detected: " + result.getMessage()); } // Array length mismatch String shortArray = "{items:[1,2]}"; String longArray = "{items:[1,2,3,4,5]}"; result = JSONCompare.compareJSON(shortArray, longArray, JSONCompareMode.STRICT); System.out.println(result.getMessage()); // Output shows array size difference ``` -------------------------------- ### Assert JSON equality with JSONassert Source: https://github.com/skyscreamer/jsonassert/blob/master/README.md Demonstrates how to use JSONAssert.assertEquals to compare an expected JSON string with an actual JSONObject. The strict parameter allows for flexible matching, ignoring order and extra fields when set to false. ```java JSONObject data = getRESTData("/friends/367.json"); String expected = "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}"; JSONAssert.assertEquals(expected, data, false); ``` -------------------------------- ### Add JSONassert dependency to Maven Source: https://github.com/skyscreamer/jsonassert/blob/master/README.md Configuration snippet for including the JSONassert library in a Java project using Maven's pom.xml file. ```xml org.skyscreamer jsonassert 2.0-rc1 test ``` -------------------------------- ### Validate JSON fields with RegularExpressionValueMatcher Source: https://context7.com/skyscreamer/jsonassert/llms.txt Demonstrates using RegularExpressionValueMatcher to validate JSON field values against regex patterns. Supports both static patterns defined in the constructor and dynamic patterns derived from expected values. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.Customization; import org.skyscreamer.jsonassert.RegularExpressionValueMatcher; import org.skyscreamer.jsonassert.comparator.CustomComparator; // Static pattern - pattern specified in constructor String userData = "{userId:\"user-12345\",email:\"test@example.com\"}"; CustomComparator staticPatternComparator = new CustomComparator( JSONCompareMode.STRICT, new Customization("userId", new RegularExpressionValueMatcher<>("user-\\d+")), new Customization("email", new RegularExpressionValueMatcher<>("[\\w.]+@[\\w.]+"))); // Expected values are ignored when static pattern is used JSONAssert.assertEquals("{userId:\"X\",email:\"X\"}", userData, staticPatternComparator); // Dynamic pattern - expected value IS the regex pattern RegularExpressionValueMatcher dynamicMatcher = new RegularExpressionValueMatcher<>(); CustomComparator dynamicPatternComparator = new CustomComparator( JSONCompareMode.STRICT, new Customization("timestamp", dynamicMatcher) ); String timeData = "{timestamp:\"2024-01-15T10:30:00Z\"}"; // Expected value "\\d{4}-\\d{2}-\\d{2}.*" is used as the regex JSONAssert.assertEquals("{timestamp:\"\\\\d{4}-\\\\d{2}-\\\\d{2}.*\"}", timeData, dynamicPatternComparator); // Validate multiple fields with different patterns String apiResponse = "{" + "id:\"a1b2c3d4\"," + "version:\"1.2.3\"," + "status:\"SUCCESS\"" + "}"; CustomComparator multiPatternComparator = new CustomComparator( JSONCompareMode.STRICT, new Customization("id", new RegularExpressionValueMatcher<>("[a-z0-9]+")), new Customization("version", new RegularExpressionValueMatcher<>("\\d+\\.\\d+\\.\\d+")), new Customization("status", new RegularExpressionValueMatcher<>("SUCCESS|FAILURE|PENDING")) ); JSONAssert.assertEquals("{id:\"X\",version:\"X\",status:\"X\"}", apiResponse, multiPatternComparator); ``` -------------------------------- ### JSONCompareMode - Comparison Behavior Options (Java) Source: https://context7.com/skyscreamer/jsonassert/llms.txt Explains the `JSONCompareMode` enum, which defines four comparison modes controlling extensibility (allowing extra fields) and strict ordering (array order). The LENIENT mode is recommended for creating less brittle tests. It also shows how to dynamically modify modes and check their properties. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; String expected = "{id:1,friends:[{id:2},{id:3}]}"; String actual = "{id:1,friends:[{id:3},{id:2}],status:\"active\"}"; // LENIENT: extensible=yes, strictOrder=no // Allows extra fields, array elements can be in any order JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT); // Passes // STRICT: extensible=no, strictOrder=yes // No extra fields allowed, arrays must be in exact order // JSONAssert.assertEquals(expected, actual, JSONCompareMode.STRICT); // Fails // NON_EXTENSIBLE: extensible=no, strictOrder=no // No extra fields allowed, but array order doesn't matter String expectedNoExtra = "{id:1,friends:[{id:2},{id:3}]}"; String actualNoExtra = "{id:1,friends:[{id:3},{id:2}]}"; JSONAssert.assertEquals(expectedNoExtra, actualNoExtra, JSONCompareMode.NON_EXTENSIBLE); // Passes // STRICT_ORDER: extensible=yes, strictOrder=yes // Extra fields allowed, but arrays must be in exact order String expectedOrdered = "{id:1,items:[1,2,3]}"; String actualOrdered = "{id:1,items:[1,2,3],count:3}"; JSONAssert.assertEquals(expectedOrdered, actualOrdered, JSONCompareMode.STRICT_ORDER); // Passes // Modify compare mode dynamically JSONCompareMode mode = JSONCompareMode.LENIENT; JSONCompareMode strictOrderMode = mode.withStrictOrdering(true); // Returns STRICT_ORDER JSONCompareMode nonExtensibleMode = mode.withExtensible(false); // Returns NON_EXTENSIBLE // Check mode properties boolean isExtensible = JSONCompareMode.LENIENT.isExtensible(); // true boolean hasStrictOrder = JSONCompareMode.STRICT.hasStrictOrder(); // true ``` -------------------------------- ### JSONCompare.compareJSON - Programmatic JSON Comparison Source: https://context7.com/skyscreamer/jsonassert/llms.txt Compares two JSON documents and returns a JSONCompareResult object for programmatic inspection, rather than throwing exceptions. This is useful for custom validation logic, generating reports, or integrating with non-JUnit test frameworks. It allows detailed analysis of comparison failures, including field mismatches, missing fields, and unexpected fields. ```java import org.skyscreamer.jsonassert.JSONCompare; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.JSONCompareResult; import org.skyscreamer.jsonassert.FieldComparisonFailure; import org.json.JSONObject; String expected = "{name:\"Pat\",age:30}"; String actual = "{name:\"Sue\",age:30,city:\"NYC\"}"; // Get comparison result without throwing exception JSONCompareResult result = JSONCompare.compareJSON(expected, actual, JSONCompareMode.STRICT); // Check if comparison passed or failed if (result.failed()) { System.out.println("Comparison failed: " + result.getMessage()); // Get detailed field failures for (FieldComparisonFailure failure : result.getFieldFailures()) { System.out.println("Field: " + failure.getField()); System.out.println("Expected: " + failure.getExpected()); System.out.println("Actual: " + failure.getActual()); } // Check for missing fields for (FieldComparisonFailure missing : result.getFieldMissing()) { System.out.println("Missing field: " + missing.getField()); } // Check for unexpected fields for (FieldComparisonFailure unexpected : result.getFieldUnexpected()) { System.out.println("Unexpected field: " + unexpected.getField()); } } if (result.passed()) { System.out.println("JSON documents match!"); } // Compare JSONObject instances JSONObject expectedObj = new JSONObject("{id:1}"); JSONObject actualObj = new JSONObject("{id:1}"); JSONCompareResult objResult = JSONCompare.compareJSON(expectedObj, actualObj, JSONCompareMode.LENIENT); System.out.println("Objects match: " + objResult.passed()); // Check specific failure types System.out.println("Has field failures: " + result.isFailureOnField()); System.out.println("Has missing fields: " + result.isMissingOnField()); System.out.println("Has unexpected fields: " + result.isUnexpectedOnField()); ``` -------------------------------- ### Perform nested and complex JSON comparisons Source: https://context7.com/skyscreamer/jsonassert/llms.txt Shows how to compare deeply nested JSON structures, arrays, and mixed types. Illustrates the difference between STRICT mode (exact order) and LENIENT mode (reordering allowed). ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; // Deeply nested object comparison String deepNested = "{a:{b:{c:{d:{e:{f:{g:\"value\"}}}}}}}"; JSONAssert.assertEquals( "{a:{b:{c:{d:{e:{f:{g:\"value\"}}}}}}}", deepNested, JSONCompareMode.STRICT ); // Complex structure with nested arrays and objects String complexJson = "{" + "id:1," + "name:\"Joe\"," + "friends:[" + "{id:2,name:\"Pat\",pets:[\"dog\"]}," + "{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}" + "]," + "pets:[]" + "}"; // Strict mode: exact match including array order JSONAssert.assertEquals(complexJson, complexJson, JSONCompareMode.STRICT); // Lenient mode: reordering allowed at all levels String reorderedJson = "{" + "name:\"Joe\"," + // field order changed "friends:[" + "{id:3,name:\"Sue\",pets:[\"fish\",\"bird\"]}," + // array order changed "{id:2,name:\"Pat\",pets:[\"dog\"]}" + "]," + "pets:[]," + "id:1" + "}"; JSONAssert.assertEquals(complexJson, reorderedJson, JSONCompareMode.LENIENT); // Arrays of arrays String arrayOfArrays = "{matrix:[[1,2],[3,4],[5,6]]}"; JSONAssert.assertEquals("{matrix:[[1,2],[3,4],[5,6]]}", arrayOfArrays, JSONCompareMode.STRICT); // Lenient allows reordering at all levels String reorderedMatrix = "{matrix:[[5,6],[3,4],[1,2]]}"; JSONAssert.assertEquals("{matrix:[[1,2],[3,4],[5,6]]}", reorderedMatrix, JSONCompareMode.LENIENT); // Mixed types in arrays String mixedArray = "{data:[123,\"text\",{nested:true},[1,2,3]]}"; JSONAssert.assertEquals( "{data:[123,\"text\",{nested:true},[1,2,3]]}", mixedArray, JSONCompareMode.STRICT ); // Null value handling String withNulls = "{id:1,name:null,data:{value:null}}"; JSONAssert.assertEquals("{id:1,name:null,data:{value:null}}", withNulls, JSONCompareMode.STRICT); ``` -------------------------------- ### JSONassert.assertEquals - Basic JSON Comparison (Java) Source: https://context7.com/skyscreamer/jsonassert/llms.txt Demonstrates the primary `JSONAssert.assertEquals` method for comparing JSON documents. It accepts expected and actual JSON as strings, JSONObject, or JSONArray, along with a comparison mode. This method returns silently on match or throws an AssertionError with a detailed message on mismatch. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.json.JSONObject; import org.json.JSONArray; // Basic string comparison with boolean strict flag String expected = "{id:1,name:\"Joe\"}"; String actual = "{id:1,name:\"Joe\",email:\"joe@example.com\"}"; // Lenient mode (false): allows extra fields, passes JSONAssert.assertEquals(expected, actual, false); // Strict mode (true): requires exact match, would fail due to extra "email" field // JSONAssert.assertEquals(expected, actual, true); // Throws AssertionError // Using JSONCompareMode enum for more control JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT); // Compare JSONObject instances directly JSONObject expectedObj = new JSONObject(); expectedObj.put("id", 1); expectedObj.put("name", "Joe"); JSONObject actualObj = new JSONObject(); actualObj.put("id", 1); actualObj.put("name", "Joe"); JSONAssert.assertEquals(expectedObj, actualObj, true); // Compare JSONArray instances JSONArray expectedArray = new JSONArray("[1,2,3]"); JSONArray actualArray = new JSONArray("[1,2,3]"); JSONAssert.assertEquals(expectedArray, actualArray, JSONCompareMode.STRICT); // With custom error message JSONAssert.assertEquals("User data mismatch", "{id:1}", "{id:1}", false); ``` -------------------------------- ### JSONAssert.assertNotEquals - Negative JSON Assertions Source: https://context7.com/skyscreamer/jsonassert/llms.txt Asserts that two JSON documents do not match. It is useful for verifying that changes have been made or that different inputs produce different outputs. This method throws an AssertionError if the documents match. It supports string, JSONObject, and JSONArray inputs, and can be used with different JSONCompareModes. ```java import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.json.JSONObject; import org.json.JSONArray; // String comparison - passes because values differ JSONAssert.assertNotEquals("{id:1}", "{id:2}", false); JSONAssert.assertNotEquals("{id:1}", "{id:2}", JSONCompareMode.LENIENT); // Array order matters in strict mode JSONAssert.assertNotEquals("[1,2,3]", "[1,3,2]", true); // Passes (order differs) JSONAssert.assertNotEquals("[1,2,3]", "[1,2,4]", false); // Passes (content differs) // With JSONObject instances JSONObject expected = new JSONObject(); expected.put("id", 12345); JSONObject actual = new JSONObject(); actual.put("id", 12346); JSONAssert.assertNotEquals(expected, actual, true); // Passes // With JSONArray instances JSONArray expectedArr = new JSONArray("[1,2,3]"); JSONArray actualArr = new JSONArray("[1,2,4]"); JSONAssert.assertNotEquals(expectedArr, actualArr, false); // Passes // With custom error message JSONAssert.assertNotEquals("Values should differ", "{id:1}", "{id:2}", false); // Verify extra fields make difference in strict mode JSONAssert.assertNotEquals("{id:1,name:\"Joe\"}", "{id:1}", JSONCompareMode.STRICT); // Passes ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.