0
# JSON Comparison
1
2
Low-level comparison functionality that provides programmatic access to JSON comparison results without JUnit integration. These methods return `JSONCompareResult` objects containing detailed comparison information, making them useful for custom test frameworks or validation logic where you need to inspect comparison results rather than just pass/fail assertions.
3
4
## Capabilities
5
6
### String Comparison
7
8
Compare JSON strings and return detailed comparison results including specific field differences, missing fields, and unexpected fields.
9
10
```java { .api }
11
public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONCompareMode mode) throws JSONException;
12
public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator) throws JSONException;
13
```
14
15
**Usage Examples:**
16
17
```java
18
import org.skyscreamer.jsonassert.JSONCompare;
19
import org.skyscreamer.jsonassert.JSONCompareResult;
20
import org.skyscreamer.jsonassert.JSONCompareMode;
21
22
// Compare with mode
23
JSONCompareResult result = JSONCompare.compareJSON(
24
"{\"name\":\"John\",\"age\":30}",
25
"{\"name\":\"Jane\",\"age\":30,\"city\":\"NYC\"}",
26
JSONCompareMode.LENIENT
27
);
28
29
if (result.failed()) {
30
System.out.println("Comparison failed: " + result.getMessage());
31
32
// Get specific failure details
33
for (FieldComparisonFailure failure : result.getFieldFailures()) {
34
System.out.println("Field: " + failure.getField());
35
System.out.println("Expected: " + failure.getExpected());
36
System.out.println("Actual: " + failure.getActual());
37
}
38
}
39
40
// Compare with custom comparator
41
CustomComparator customComparator = new CustomComparator(JSONCompareMode.LENIENT);
42
result = JSONCompare.compareJSON(expected, actual, customComparator);
43
```
44
45
### JSONObject Comparison
46
47
Direct comparison between JSONObject instances with customizable comparison strategies.
48
49
```java { .api }
50
public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONCompareMode mode) throws JSONException;
51
public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONComparator comparator) throws JSONException;
52
```
53
54
**Usage Examples:**
55
56
```java
57
JSONObject expected = new JSONObject("{\"id\":1,\"name\":\"John\"}");
58
JSONObject actual = new JSONObject("{\"id\":1,\"name\":\"John\",\"active\":true}");
59
60
// Compare with different modes
61
JSONCompareResult strict = JSONCompare.compareJSON(expected, actual, JSONCompareMode.STRICT);
62
JSONCompareResult lenient = JSONCompare.compareJSON(expected, actual, JSONCompareMode.LENIENT);
63
64
System.out.println("Strict passed: " + strict.passed()); // false - extra field
65
System.out.println("Lenient passed: " + lenient.passed()); // true - extra field allowed
66
```
67
68
### JSONArray Comparison
69
70
Compare JSONArray instances with flexible element ordering and matching strategies.
71
72
```java { .api }
73
public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONCompareMode mode) throws JSONException;
74
public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONComparator comparator) throws JSONException;
75
```
76
77
**Usage Examples:**
78
79
```java
80
JSONArray expected = new JSONArray("[{\"id\":1},{\"id\":2}]");
81
JSONArray actual = new JSONArray("[{\"id\":2},{\"id\":1}]");
82
83
// Different ordering behavior
84
JSONCompareResult strictOrder = JSONCompare.compareJSON(expected, actual, JSONCompareMode.STRICT_ORDER);
85
JSONCompareResult lenient = JSONCompare.compareJSON(expected, actual, JSONCompareMode.LENIENT);
86
87
System.out.println("Strict order passed: " + strictOrder.passed()); // false - different order
88
System.out.println("Lenient passed: " + lenient.passed()); // true - order doesn't matter
89
```
90
91
### JSONString Comparison
92
93
Compare JSONString objects by their JSON string representations.
94
95
```java { .api }
96
public static JSONCompareResult compareJson(JSONString expected, JSONString actual);
97
```
98
99
**Usage Examples:**
100
101
```java
102
import org.json.JSONString;
103
104
JSONString expected = new JSONString() {
105
public String toJSONString() { return "{\"value\":\"test\"}"; }
106
};
107
108
JSONString actual = new JSONString() {
109
public String toJSONString() { return "{\"value\":\"test\"}"; }
110
};
111
112
JSONCompareResult result = JSONCompare.compareJson(expected, actual);
113
System.out.println("JSONString comparison passed: " + result.passed());
114
```
115
116
## Working with Results
117
118
The `JSONCompareResult` class provides detailed information about comparison outcomes:
119
120
### Basic Result Information
121
122
```java
123
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, JSONCompareMode.LENIENT);
124
125
// Check overall result
126
boolean success = result.passed();
127
boolean failure = result.failed();
128
String message = result.getMessage(); // Detailed failure description
129
```
130
131
### Field-Level Failure Analysis
132
133
```java
134
// Get different types of field failures
135
List<FieldComparisonFailure> fieldFailures = result.getFieldFailures(); // Value mismatches
136
List<FieldComparisonFailure> missingFields = result.getFieldMissing(); // Expected but not found
137
List<FieldComparisonFailure> unexpectedFields = result.getFieldUnexpected(); // Found but not expected
138
139
// Check for specific failure types
140
boolean hasFieldFailures = result.isFailureOnField();
141
boolean hasMissingFields = result.isMissingOnField();
142
boolean hasUnexpectedFields = result.isUnexpectedOnField();
143
144
// Process individual failures
145
for (FieldComparisonFailure failure : fieldFailures) {
146
String fieldPath = failure.getField();
147
Object expectedValue = failure.getExpected();
148
Object actualValue = failure.getActual();
149
150
System.out.println("Field " + fieldPath + " failed:");
151
System.out.println(" Expected: " + expectedValue);
152
System.out.println(" Actual: " + actualValue);
153
}
154
```
155
156
### Advanced Comparison Scenarios
157
158
```java
159
// Using comparison results for custom validation logic
160
public boolean isJsonValid(String expected, String actual) {
161
try {
162
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, JSONCompareMode.LENIENT);
163
164
if (result.passed()) {
165
return true;
166
}
167
168
// Allow certain types of differences
169
if (result.isUnexpectedOnField() && !result.isFailureOnField() && !result.isMissingOnField()) {
170
// Only extra fields, which might be acceptable
171
return true;
172
}
173
174
return false;
175
} catch (JSONException e) {
176
return false;
177
}
178
}
179
180
// Custom error reporting
181
public void reportJsonDifferences(String expected, String actual) throws JSONException {
182
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, JSONCompareMode.STRICT);
183
184
if (result.failed()) {
185
System.out.println("JSON Comparison Failed:");
186
System.out.println("Overall message: " + result.getMessage());
187
188
if (result.isFailureOnField()) {
189
System.out.println("\nField value mismatches:");
190
result.getFieldFailures().forEach(f ->
191
System.out.println(" " + f.getField() + ": expected " + f.getExpected() + ", got " + f.getActual())
192
);
193
}
194
195
if (result.isMissingOnField()) {
196
System.out.println("\nMissing fields:");
197
result.getFieldMissing().forEach(f ->
198
System.out.println(" " + f.getField() + ": expected " + f.getExpected())
199
);
200
}
201
202
if (result.isUnexpectedOnField()) {
203
System.out.println("\nUnexpected fields:");
204
result.getFieldUnexpected().forEach(f ->
205
System.out.println(" " + f.getField() + ": got " + f.getActual())
206
);
207
}
208
}
209
}
210
```
211
212
## Error Handling
213
214
- **JSONException**: Thrown when JSON parsing fails for either expected or actual values
215
- **IllegalArgumentException**: Thrown when expected and actual JSON types don't match (e.g., comparing object to array)
216
217
## Integration with Assertions
218
219
The JSONCompare methods serve as the backend for JSONAssert. The assertion methods use these comparison functions and throw AssertionError when `result.failed()` returns true:
220
221
```java
222
// This assertion method internally uses:
223
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
224
if (result.failed()) {
225
throw new AssertionError(result.getMessage());
226
}
227
```