diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml
new file mode 100644
index 00000000..fb527d76
--- /dev/null
+++ b/.github/workflows/deploy-website.yml
@@ -0,0 +1,50 @@
+# Simple workflow for deploying static content to GitHub Pages
+name: Deploy static content to Pages
+
+on:
+ # Runs on pushes targeting the default branch - disabled, manual only
+ #push:
+ # branches: ["master"]
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
+# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+concurrency:
+ group: "pages"
+ cancel-in-progress: false
+
+jobs:
+ # Single deploy job since we're just deploying
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Setup Pages
+ uses: actions/configure-pages@v5
+ - uses: actions/setup-java@v4
+ with:
+ java-version: '17'
+ distribution: 'temurin'
+ cache: maven
+ - name: Run the Maven javadoc command
+ run: mvn javadoc:aggregate -DreportOutputDirectory=src/site/resources/apidocs
+ - name: Upload artifact
+ uses: actions/upload-pages-artifact@v3
+ with:
+ # Upload entire repository
+ path: './src/site/resources'
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..ec376bb8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.idea
+target
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a277cef1..1b33ee64 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,41 @@
Changelog
=========
+Version 2.0-rc1 - 7/28/2024
+-------------------
+ - Release candidate
+ - ** Switches JSON implementation to use org.json:json:20240303 **
+ - Deployment still built with Java version 8 to maximize compatibility
+ - Cannot insert null directly into JSONArray without casting. Recommend to use JSONObject.Null
+ - JSONException is now a RuntimeException. Is not defined as thrown in method signatures anynmore.
+
+Version 1.5.3 - 6/28/2024
+-------------------------
+ - Revert Java release version from 21 to 8 due to breaking older compilers.
+
+Version 1.5.2 - 6/14/2024
+-------------------------
+ - Fix CVE-2020-15250 JUnit vulnerability (https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15250). Bump
+ dependencies.
+ - Add gitIgnore file
+ - README syntax error fix
+ - Accidentally upgraded release to Java version 21
+
+Version 1.5.1 - 7/4/2022
+------------------------
+Going to try to catch up on some ancient PRs, mainly around security and cleanup. Starting with accepted PRs that
+didn't get released yet. To be followed hopefully shortly with another release.
+ - Added convenience methods for JSONObject comparison using a custom JSONComparator (thanks jakob-o@!)
+ - Fix issue #105: Issue when comparing JSONArray if any value is null (thanks suraj1291993@!)
+ - Fixes security vulnerability associated with older version of junit
+
+Version 1.5.0 - 3/19/2017
+-------------------------
+ - JSONassert now supports user-supplied error messages (thanks yasin3061@!)
+ - Some refactoring / code health cleanup (thanks picimako@!)
+ - License headers on individual files
+ - Java 8 friendly javadocs
+
Version 1.4.0 - 10/30/2016
--------------------------
- Change the implementation for org.json to one with a more open license
@@ -9,16 +44,16 @@ Version 1.4.0 - 10/30/2016
Version 1.3.0 - 12/16/2015
--------------------------
- - Fix & improve ArrayValueMatcher JavaDoc (dmackinder)
+ - Fix & improve ArrayValueMatcher JavaDoc (thanks dmackinder@!)
Fix final JavaDoc example and add new example showing how to verify
every array element using a custom comparator
- - Fix URL in pom.xml (aukevanleeuwen)
- - Update JSONCompareResult.java adding 2 new lists for missing and unexpected fileds (riccorazza)
- - Includes missing imports in test class (javierseixas)
+ - Fix URL in pom.xml (aukevanleeuwen@)
+ - Update JSONCompareResult.java adding 2 new lists for missing and unexpected fileds (thanks riccorazza@!)
+ - Includes missing imports in test class (thanks javierseixas@!)
Version 1.2.3 - 2/5/2014
------------------------
- - This edition brought to you by dmackinder (thanks!)
+ - This edition brought to you by dmackinder (thanks dmackinder!)
- Added array size comparator enhancements.
- Added ArrayValueMatcher to simplify verification of range of array elements.
- Improve diagnostics from RegularExpressionValueMatcher.
@@ -31,7 +66,8 @@ Version 1.2.2 - 12/31/2013
Version 1.2.1 - 10/24/2013
--------------------------
- Remove commons-collection dependency
- - Updated Customization class to allow path-matching, and matching of expected and actual values with user-provided EqualityComparator.
+ - Updated Customization class to allow path-matching, and matching of expected and actual values with user-provided
+ EqualityComparator.
- Added AssertNotEquals
Version 1.2.0 - 3/17/2013
diff --git a/README.md b/README.md
index 77a83ce6..871b1e19 100644
--- a/README.md
+++ b/README.md
@@ -29,22 +29,23 @@ Assert.assertTrue(data.has("friends"));
Object friendsObject = data.get("friends");
Assert.assertTrue(friendsObject instanceof JSONArray);
JSONArray friends = (JSONArray) friendsObject;
-Assert.assertEquals(2, data.length());
-JSONObject friend1Obj = friends.getJSONObject(data.get(0));
-Assert.true(friend1Obj.has("id"));
-Assert.true(friend1Obj.has("name"));
-JSONObject friend2Obj = friends.getJSONObject(data.get(1));
-Assert.true(friend2Obj.has("id"));
-Assert.true(friend2Obj.has("name"));
+Assert.assertEquals(2, friends.length());
+JSONObject friend1Obj = friends.getJSONObject(0);
+Assert.assertTrue(friend1Obj.has("id"));
+Assert.assertTrue(friend1Obj.has("name"));
+JSONObject friend2Obj = friends.getJSONObject(1);
+Assert.assertTrue(friend2Obj.has("id"));
+Assert.assertTrue(friend2Obj.has("name"));
+
if ("Carter Page".equals(friend1Obj.getString("name"))) {
- Assert.assertEquals(123, friend1Obj.getInt("id"));
+ Assert.assertEquals(456, friend1Obj.getInt("id"));
Assert.assertEquals("Corby Page", friend2Obj.getString("name"));
- Assert.assertEquals(456, friend2Obj.getInt("id"));
+ Assert.assertEquals(123, friend2Obj.getInt("id"));
}
else if ("Corby Page".equals(friend1Obj.getString("name"))) {
- Assert.assertEquals(456, friend1Obj.getInt("id"));
+ Assert.assertEquals(123, friend1Obj.getInt("id"));
Assert.assertEquals("Carter Page", friend2Obj.getString("name"));
- Assert.assertEquals(123, friend2Obj.getInt("id"));
+ Assert.assertEquals(456, friend2Obj.getInt("id"));
}
else {
Assert.fail("Expected either Carter or Corby, Got: " + friend1Obj.getString("name"));
@@ -76,8 +77,8 @@ To use, [download the JAR](https://github.com/skyscreamer/JSONassert/releases) o
org.skyscreamerjsonassert
- 1.4.0
- test
+ 2.0-rc1
+ test
Write tests like this:
@@ -96,16 +97,15 @@ Who uses JSONassert?
+ [GroupDocs](http://groupdocs.com/)
+ [Shazam](http://www.shazam.com/)
+ [Thucydides](http://thucydides.net/)
+ + [and over a thousand more](https://mvnrepository.com/artifact/org.skyscreamer/jsonassert)...
* * *
org.json
--------
-This implementation uses a clean-room implementation of the org.json
-library implemented for the Android system, released under the Apache 2.0 license. See
-[com.vaadin.external.google:android-json](http://search.maven.org/#artifactdetails%7Ccom.vaadin.external.google%7Candroid-json%7C0.0.20131108.vaadin1%7Cjar)
-That jar does **not** include the org.json.JSONString interface, so a new implementation of that interface is added to this source.
+As of v2, JSONAssert uses @stleary's [JSON-java](https://github.com/stleary/JSON-java) implementation of org.json, the
+most commonly used reference implementation for JSON in Java.
Resources
---------
diff --git a/pom.xml b/pom.xml
index eb99a8df..86738534 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,21 +2,19 @@
4.0.0
-
- org.sonatype.oss
- oss-parent
- 7
-
-
org.skyscreamerjsonassert
- 1.4.1-SNAPSHOT
+ 2.0-rc1jarJSONassert
- A library to develop RESTful but flexible APIs
+ Write JSON unit tests in less code. Great for testing REST interfaces.https://github.com/skyscreamer/JSONassert
+
+ 8
+
+
The Apache Software License, Version 2.0
@@ -36,28 +34,28 @@
carter@skyscreamer.org
- cepage
- Corby Page
- corby@skyscreamer.org
-
-
- sduskis
- Solomon Duskis
- solomon@skyscreamer.org
+ hertzsprung
+ James Shaw
- com.vaadin.external.google
- android-json
- 0.0.20131108.vaadin1
+ org.json
+ json
+ 20240303junitjunit
- 4.10
+ 4.13.2
+ test
+
+
+ org.hamcrest
+ hamcrest
+ 2.2test
@@ -67,44 +65,27 @@
org.apache.maven.pluginsmaven-compiler-plugin
- 2.3.1
-
- 1.6
- 1.6
-
+ 3.11.0
- org.apache.maven.plugins
- maven-site-plugin
- 3.3
+ org.sonatype.plugins
+ nexus-staging-maven-plugin
+ 1.6.7
+ true
-
-
- org.codehaus.mojo
- cobertura-maven-plugin
- 2.5.1
-
-
+ ossrh
+ https://oss.sonatype.org/
+ false
+
+
+ com.thoughtworks.xstream
+ xstream
+ 1.4.15
+
+
-
-
- org.apache.maven.scm
- maven-scm-provider-gitexe
- 1.3
-
-
- org.apache.maven.scm
- maven-scm-manager-plexus
- 1.3
-
-
- org.kathrynhuxtable.maven.wagon
- wagon-gitsite
- 0.3.1
-
-
@@ -112,23 +93,51 @@
github-project-sitegitsite:git@github.com/skyscreamer/JSONassert.git
+
+ ossrh
+ https://oss.sonatype.org/content/repositories/snapshots
+
- release-sign-artifacts
-
-
- performRelease
- true
-
-
+ deploy
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 2.2.1
+
+
+ attach-sources
+
+ jar-no-fork
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.9.1
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+ ${java.home}/bin/javadoc
+ ${maven.compiler.release}
+
+ org.apache.maven.pluginsmaven-gpg-plugin
- 1.1
+ 1.5sign-artifacts
diff --git a/src/main/java/org/json/JSONString.java b/src/main/java/org/json/JSONString.java
deleted file mode 100644
index e82cc246..00000000
--- a/src/main/java/org/json/JSONString.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package org.json;
-
-/**
- * The JSONString interface allows a toJSONString() method so that a class can change
- * the behavior of JSONObject.toString(), JSONArray.toString(), and JSONWriter.value(Object).
- * The toJSONString method will be used instead of the default behavior of using the
- * Object's toString() method and quoting the result.
- *
- * @author sasdjb
- *
- */
-public interface JSONString {
-
- /**
- * The toJSONString method allows a class to produce its own JSON
- * serialization.
- * */
- public String toJSONString();
-
-}
diff --git a/src/main/java/org/skyscreamer/jsonassert/ArrayValueMatcher.java b/src/main/java/org/skyscreamer/jsonassert/ArrayValueMatcher.java
index 1ffd7a5a..2d4dd8ec 100644
--- a/src/main/java/org/skyscreamer/jsonassert/ArrayValueMatcher.java
+++ b/src/main/java/org/skyscreamer/jsonassert/ArrayValueMatcher.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import java.text.MessageFormat;
@@ -22,62 +36,73 @@
*
*
Assuming JSON to be verified is held in String variable ARRAY_OF_JSONOBJECTS and contains:
To verify that the 'id' attribute of first element of array 'a' is '1':
*
- *
- * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0));
- * JSONAssert.assertEquals("{a:[{id:1}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ *
{@code
+ * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
+ * Customization customization = new Customization("a", new ArrayValueMatcher
*
*
To simplify complexity of expected JSON string, the value "a:[{id:1}]}" may be replaced by "a:{id:1}}"
*
*
To verify that the 'type' attribute of second and third elements of array 'a' is 'row':
*
- *
- * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1, 2));
- * JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ *
{@code
+ * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
+ * Customization customization = new Customization("a", new ArrayValueMatcher
*
*
To verify that the 'type' attribute of every element of array 'a' is 'row':
*
- *
- * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));
- * JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ *
{@code
+ * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
+ * Customization customization = new Customization("a", new ArrayValueMatcher
*
*
To verify that the 'id' attribute of every element of array 'a' matches regular expression '\d+'. This requires a custom comparator to specify regular expression to be used to validate each array element, hence the array of Customization instances:
*
- *
- * // get length of array we will verify
- * int aLength = ((JSONArray)((JSONObject)JSONParser.parseJSON(ARRAY_OF_JSONOBJECTS)).get("a")).length();
- * // create array of customizations one for each array element
- * RegularExpressionValueMatcher<Object> regExValueMatcher = new RegularExpressionValueMatcher<Object>("\\d+"); // matches one or more digits
- * Customization[] customizations = new Customization[aLength];
- * for (int i=0; i<aLength; i++) {
- * String contextPath = "a["+i+"].id";
- * customizations[i] = new Customization(contextPath, regExValueMatcher);
- * }
- * CustomComparator regExComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER, customizations);
- * ArrayValueMatcher<Object> regExArrayValueMatcher = new ArrayValueMatcher<Object>(regExComparator);
- * Customization regExArrayValueCustomization = new Customization("a", regExArrayValueMatcher);
- * CustomComparator regExCustomArrayValueComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER, new Customization[] { regExArrayValueCustomization });
- * JSONAssert.assertEquals("{a:[{id:X}]}", ARRAY_OF_JSONOBJECTS, regExCustomArrayValueComparator);
- *
+ *
{@code
+ * // get length of array we will verify
+ * int aLength = ((JSONArray)((JSONObject)JSONParser.parseJSON(ARRAY_OF_JSONOBJECTS)).get("a")).length();
+ * // create array of customizations one for each array element
+ * RegularExpressionValueMatcher
*
*
To verify that the 'background' attribute of every element of array 'a' alternates between 'white' and 'grey' starting with first element 'background' being 'white':
*
- *
- * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));
- * JSONAssert.assertEquals("{a:[{background:white},{background:grey}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ *
{@code
+ * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);
+ * Customization customization = new Customization("a", new ArrayValueMatcher(comparator));
+ * JSONAssert.assertEquals("{a:[{background:white},{background:grey}]}", ARRAY_OF_JSONOBJECTS,
+ * new CustomComparator(JSONCompareMode.LENIENT, customization));
+ * }
*
*
Assuming JSON to be verified is held in String variable ARRAY_OF_JSONARRAYS and contains:
*
@@ -87,28 +112,28 @@
*
*
To verify that the first three elements of JSON array 'a' are JSON arrays of length 3:
*
- *
- * JSONComparator comparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0, 2));
+ *
{@code
+ * JSONComparator comparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);
+ * Customization customization = new Customization("a", new ArrayValueMatcher(comparator, 0, 2));
* JSONAssert.assertEquals("{a:[[3]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ * }
*
*
NOTE: simplified expected JSON strings are not possible in this case as ArraySizeComparator does not support them.
*
*
To verify that the second elements of JSON array 'a' is a JSON array whose first element has the value 9:
*
- *
- * JSONComparator innerComparator = new DefaultComparator(JSONCompareMode.LENIENT);
- * Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher<Object>(innerComparator, 0));
- * JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);
- * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1));
+ *
{@code
+ * JSONComparator innerComparator = new DefaultComparator(JSONCompareMode.LENIENT);
+ * Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher(innerComparator, 0));
+ * JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);
+ * Customization customization = new Customization("a", new ArrayValueMatcher(comparator, 1));
* JSONAssert.assertEquals("{a:[[9]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));
- *
+ * }
*
*
To simplify complexity of expected JSON string, the value "{a:[[9]]}" may be replaced by "{a:[9]}" or "{a:9}"
*
* @author Duncan Mackinder
- *
+ * @param Array Type
*/
public class ArrayValueMatcher implements LocationAwareValueMatcher {
private final JSONComparator comparator;
@@ -147,8 +172,8 @@ public ArrayValueMatcher(JSONComparator comparator, int index) {
*
* @param comparator
* comparator to use to compare elements
- * @from first element in actual array to compared
- * @to last element in actual array to compared
+ * @param from first element in actual array to compared
+ * @param to last element in actual array to compared
*/
public ArrayValueMatcher(JSONComparator comparator, int from, int to) {
assert comparator != null : "comparator null";
diff --git a/src/main/java/org/skyscreamer/jsonassert/Customization.java b/src/main/java/org/skyscreamer/jsonassert/Customization.java
index d2e38d53..c812a447 100644
--- a/src/main/java/org/skyscreamer/jsonassert/Customization.java
+++ b/src/main/java/org/skyscreamer/jsonassert/Customization.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import java.util.regex.Pattern;
@@ -24,18 +38,7 @@ private String buildPatternLevel1(String path) {
String regex = "\\*\\*\\.";
String replacement = "(?:.+\\.)?";
- StringBuilder sb = new StringBuilder();
- String[] parts = path.split(regex);
- for (int i = 0; i < parts.length; i++) {
- String part = parts[i];
-
- sb.append(buildPatternLevel2(part));
- if (i < parts.length - 1) {
- sb.append(replacement);
- }
- }
-
- return sb.toString();
+ return buildPattern(path, regex, replacement, 1);
}
private String buildPatternLevel2(String s) {
@@ -45,17 +48,7 @@ private String buildPatternLevel2(String s) {
String regex = "\\*\\*";
String replacement = ".+";
- StringBuilder sb = new StringBuilder();
- String[] parts = s.split(regex);
- for (int i = 0; i < parts.length; i++) {
- String part = parts[i];
-
- sb.append(buildPatternLevel3(part));
- if (i < parts.length - 1) {
- sb.append(replacement);
- }
- }
- return sb.toString();
+ return buildPattern(s, regex, replacement, 2);
}
private String buildPatternLevel3(String s) {
@@ -66,19 +59,41 @@ private String buildPatternLevel3(String s) {
String regex = "\\*";
String replacement = "[^\\.]+";
+ return buildPattern(s, regex, replacement, 3);
+ }
+
+ private String buildPattern(String path, String regex, String replacement, int level) {
StringBuilder sb = new StringBuilder();
- String[] parts = s.split(regex);
+ String[] parts = path.split(regex);
for (int i = 0; i < parts.length; i++) {
- String part = parts[i];
-
- sb.append(Pattern.quote(part));
+ sb.append(buildPatternForLevel(level, parts[i]));
if (i < parts.length - 1) {
sb.append(replacement);
- }
- }
+ }
+ }
return sb.toString();
}
+ private String buildPatternForLevel(int level, String part) {
+ switch (level) {
+ case 1:
+ return buildPatternLevel2(part);
+ case 2:
+ return buildPatternLevel3(part);
+ case 3:
+ return Pattern.quote(part);
+ default:
+ return "Incorrect level.";
+ }
+ }
+
+ /**
+ * Creates a new {@link Customization} instance for {@code path} and {@code comparator}.
+ *
+ * @param path the json path
+ * @param comparator the comparator
+ * @return a new Customization
+ */
public static Customization customization(String path, ValueMatcher comparator) {
return new Customization(path, comparator);
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/FieldComparisonFailure.java b/src/main/java/org/skyscreamer/jsonassert/FieldComparisonFailure.java
index 73d5b4d9..a4746f24 100644
--- a/src/main/java/org/skyscreamer/jsonassert/FieldComparisonFailure.java
+++ b/src/main/java/org/skyscreamer/jsonassert/FieldComparisonFailure.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
/**
diff --git a/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java b/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
index 342d5d30..5a2eec18 100644
--- a/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
+++ b/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
@@ -1,7 +1,20 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
@@ -45,28 +58,52 @@ private JSONAssert() {}
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, JSONObject actual, boolean strict)
- throws JSONException {
+ public static void assertEquals(String expectedStr, JSONObject actual, boolean strict) {
assertEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONObject provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONObject to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertEquals(String message, String expectedStr, JSONObject actual, boolean strict) {
+ assertEquals(message, expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONObject provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
- * @see #assertEquals(String JSONObject, boolean)
+ * @see #assertEquals(String, JSONObject, boolean)
*
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, JSONObject actual, boolean strict)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, JSONObject actual, boolean strict) {
assertNotEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @see #assertEquals(String, JSONObject, boolean)
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONObject to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertNotEquals(String message, String expectedStr, JSONObject actual, boolean strict) {
+ assertNotEquals(message, expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONObject provided matches the expected string. If it isn't it throws an
@@ -75,13 +112,25 @@ public static void assertNotEquals(String expectedStr, JSONObject actual, boolea
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode) {
+ assertEquals("", expectedStr, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONObject provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONObject to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertEquals(String message, String expectedStr, JSONObject actual, JSONCompareMode compareMode)
+ {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONObject) {
- assertEquals((JSONObject)expected, actual, compareMode);
+ assertEquals(message, (JSONObject)expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON array, but passing in a JSON object");
@@ -97,13 +146,27 @@ public static void assertEquals(String expectedStr, JSONObject actual, JSONCompa
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode) {
+ assertNotEquals("", expectedStr, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @see #assertEquals(String, JSONObject, JSONCompareMode)
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONObject to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertNotEquals(String message, String expectedStr, JSONObject actual,
+ JSONCompareMode compareMode) {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONObject) {
- assertNotEquals((JSONObject) expected, actual, compareMode);
+ assertNotEquals(message, (JSONObject) expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON array, but passing in a JSON object");
@@ -117,12 +180,23 @@ public static void assertNotEquals(String expectedStr, JSONObject actual, JSONCo
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, JSONArray actual, boolean strict)
- throws JSONException {
+ public static void assertEquals(String expectedStr, JSONArray actual, boolean strict) {
assertEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONArray to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertEquals(String message, String expectedStr, JSONArray actual, boolean strict) {
+ assertEquals(message, expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
@@ -131,12 +205,23 @@ public static void assertEquals(String expectedStr, JSONArray actual, boolean st
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, JSONArray actual, boolean strict)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, JSONArray actual, boolean strict) {
assertNotEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONArray to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertNotEquals(String message, String expectedStr, JSONArray actual, boolean strict) {
+ assertNotEquals(message, expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
@@ -145,13 +230,24 @@ public static void assertNotEquals(String expectedStr, JSONArray actual, boolean
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode) {
+ assertEquals("", expectedStr, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONArray to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertEquals(String message, String expectedStr, JSONArray actual, JSONCompareMode compareMode) {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONArray) {
- assertEquals((JSONArray) expected, actual, compareMode);
+ assertEquals(message, (JSONArray) expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON object, but passing in a JSON array");
@@ -165,10 +261,8 @@ public static void assertEquals(String expectedStr, JSONArray actual, JSONCompar
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode) {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONArray) {
assertNotEquals((JSONArray) expected, actual, compareMode);
@@ -177,6 +271,26 @@ public static void assertNotEquals(String expectedStr, JSONArray actual, JSONCom
throw new AssertionError("Expecting a JSON object, but passing in a JSON array");
}
}
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actual JSONArray to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertNotEquals(String message, String expectedStr, JSONArray actual,
+ JSONCompareMode compareMode) {
+ Object expected = JSONParser.parseJSON(expectedStr);
+ if (expected instanceof JSONArray) {
+ assertNotEquals(message, (JSONArray) expected, actual, compareMode);
+ }
+ else {
+ throw new AssertionError("Expecting a JSON object, but passing in a JSON array");
+ }
+ }
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
@@ -185,12 +299,23 @@ public static void assertNotEquals(String expectedStr, JSONArray actual, JSONCom
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, String actualStr, boolean strict)
- throws JSONException {
+ public static void assertEquals(String expectedStr, String actualStr, boolean strict) {
assertEquals(expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertEquals(String message, String expectedStr, String actualStr, boolean strict) {
+ assertEquals(message, expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
@@ -199,12 +324,23 @@ public static void assertEquals(String expectedStr, String actualStr, boolean st
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, String actualStr, boolean strict)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, String actualStr, boolean strict) {
assertNotEquals(expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertNotEquals(String message, String expectedStr, String actualStr, boolean strict) {
+ assertNotEquals(message, expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
@@ -213,10 +349,21 @@ public static void assertNotEquals(String expectedStr, String actualStr, boolean
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, String actualStr, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertEquals(String expectedStr, String actualStr, JSONCompareMode compareMode) {
+ assertEquals("", expectedStr, actualStr, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode) {
if (expectedStr==actualStr) return;
if (expectedStr==null){
throw new AssertionError("Expected string is null.");
@@ -225,7 +372,7 @@ public static void assertEquals(String expectedStr, String actualStr, JSONCompar
}
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.failed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -236,13 +383,25 @@ public static void assertEquals(String expectedStr, String actualStr, JSONCompar
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, String actualStr, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, String actualStr, JSONCompareMode compareMode) {
+ assertNotEquals("", expectedStr, actualStr, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertNotEquals(String message, String expectedStr, String actualStr,
+ JSONCompareMode compareMode) {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -253,13 +412,25 @@ public static void assertNotEquals(String expectedStr, String actualStr, JSONCom
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
- * @throws JSONException
*/
- public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator)
- throws JSONException {
+ public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator) {
+ assertEquals("", expectedStr, actualStr, comparator);
+
+ }
+
+ /**
+ * Asserts that the json string provided matches the expected string. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param comparator Comparator
+ */
+ public static void assertEquals(String message, String expectedStr, String actualStr, JSONComparator comparator) {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.failed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -270,16 +441,85 @@ public static void assertEquals(String expectedStr, String actualStr, JSONCompar
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
- * @throws JSONException
*/
- public static void assertNotEquals(String expectedStr, String actualStr, JSONComparator comparator)
- throws JSONException {
+ public static void assertNotEquals(String expectedStr, String actualStr, JSONComparator comparator) {
+ assertNotEquals("", expectedStr, actualStr, comparator);
+ }
+
+ /**
+ * Asserts that the json string provided does not match the expected string. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expectedStr Expected JSON string
+ * @param actualStr String to compare
+ * @param comparator Comparator
+ */
+ public static void assertNotEquals(String message, String expectedStr, String actualStr,
+ JSONComparator comparator) {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.passed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
+ /**
+ * Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param comparator Comparator
+ */
+ public static void assertEquals(JSONObject expected, JSONObject actual, JSONComparator comparator) {
+ assertEquals("", expected, actual, comparator);
+ }
+
+ /**
+ * Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param comparator Comparator
+ */
+ public static void assertEquals(String message, JSONObject expected, JSONObject actual, JSONComparator comparator) {
+ JSONCompareResult result = JSONCompare.compareJSON(expected, actual, comparator);
+ if (result.failed()) {
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
+ }
+ }
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param comparator Comparator
+ */
+ public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONComparator comparator) {
+ assertNotEquals("", expected, actual, comparator);
+ }
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param comparator Comparator
+ */
+ public static void assertNotEquals(String message, JSONObject expected, JSONObject actual,
+ JSONComparator comparator) {
+ JSONCompareResult result = JSONCompare.compareJSON(expected, actual, comparator);
+ if (result.passed()) {
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
+ }
+ }
+
/**
* Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
* {@link AssertionError}.
@@ -287,12 +527,23 @@ public static void assertNotEquals(String expectedStr, String actualStr, JSONCom
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertEquals(JSONObject expected, JSONObject actual, boolean strict)
- throws JSONException {
+ public static void assertEquals(JSONObject expected, JSONObject actual, boolean strict) {
assertEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertEquals(String message, JSONObject expected, JSONObject actual, boolean strict) {
+ assertEquals(message, expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
@@ -301,12 +552,23 @@ public static void assertEquals(JSONObject expected, JSONObject actual, boolean
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertNotEquals(JSONObject expected, JSONObject actual, boolean strict)
- throws JSONException {
+ public static void assertNotEquals(JSONObject expected, JSONObject actual, boolean strict) {
assertNotEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertNotEquals(String message, JSONObject expected, JSONObject actual, boolean strict) {
+ assertNotEquals(message, expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
@@ -315,14 +577,25 @@ public static void assertNotEquals(JSONObject expected, JSONObject actual, boole
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode)
- throws JSONException
- {
+ public static void assertEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode) {
+ assertEquals("", expected, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertEquals(String message, JSONObject expected, JSONObject actual,
+ JSONCompareMode compareMode) {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.failed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -333,14 +606,25 @@ public static void assertEquals(JSONObject expected, JSONObject actual, JSONComp
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode)
- throws JSONException
- {
+ public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode) {
+ assertNotEquals("", expected, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONObject
+ * @param actual JSONObject to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertNotEquals(String message, JSONObject expected, JSONObject actual,
+ JSONCompareMode compareMode) {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.passed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -351,11 +635,22 @@ public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONC
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertEquals(JSONArray expected, JSONArray actual, boolean strict)
- throws JSONException {
- assertEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ public static void assertEquals(JSONArray expected, JSONArray actual, boolean strict) {
+ assertEquals("", expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
+
+ /**
+ * Asserts that the JSONArray provided matches the expected JSONArray. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONArray
+ * @param actual JSONArray to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertEquals(String message, JSONArray expected, JSONArray actual, boolean strict) {
+ assertEquals(message, expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
@@ -365,12 +660,23 @@ public static void assertEquals(JSONArray expected, JSONArray actual, boolean st
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param strict Enables strict checking
- * @throws JSONException
*/
- public static void assertNotEquals(JSONArray expected, JSONArray actual, boolean strict)
- throws JSONException {
+ public static void assertNotEquals(JSONArray expected, JSONArray actual, boolean strict) {
assertNotEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected JSONArray. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONArray
+ * @param actual JSONArray to compare
+ * @param strict Enables strict checking
+ */
+ public static void assertNotEquals(String message, JSONArray expected, JSONArray actual, boolean strict) {
+ assertNotEquals(message, expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
+ }
/**
* Asserts that the JSONArray provided matches the expected JSONArray. If it isn't it throws an
@@ -379,13 +685,24 @@ public static void assertNotEquals(JSONArray expected, JSONArray actual, boolean
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode) {
+ assertEquals("", expected, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONArray provided matches the expected JSONArray. If it isn't it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONArray
+ * @param actual JSONArray to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertEquals(String message, JSONArray expected, JSONArray actual, JSONCompareMode compareMode) {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.failed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
@@ -396,13 +713,36 @@ public static void assertEquals(JSONArray expected, JSONArray actual, JSONCompar
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
- * @throws JSONException
*/
- public static void assertNotEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode)
- throws JSONException {
+ public static void assertNotEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode) {
+ assertNotEquals("", expected, actual, compareMode);
+ }
+
+ /**
+ * Asserts that the JSONArray provided does not match the expected JSONArray. If it is it throws an
+ * {@link AssertionError}.
+ *
+ * @param message Error message to be displayed in case of assertion failure
+ * @param expected Expected JSONArray
+ * @param actual JSONArray to compare
+ * @param compareMode Specifies which comparison mode to use
+ */
+ public static void assertNotEquals(String message, JSONArray expected, JSONArray actual,
+ JSONCompareMode compareMode) {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.passed()) {
- throw new AssertionError(result.getMessage());
+ throw new AssertionError(getCombinedMessage(message, result.getMessage()));
+ }
+ }
+
+ private static String getCombinedMessage(String message1, String message2) {
+ String combinedMessage = "";
+
+ if(message1 == null || "".equals(message1)) {
+ combinedMessage = message2;
+ } else {
+ combinedMessage = message1 + " " + message2;
}
+ return combinedMessage;
}
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/JSONCompare.java b/src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
index fc41bf4f..c17115df 100644
--- a/src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
+++ b/src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
@@ -1,7 +1,20 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import org.skyscreamer.jsonassert.comparator.DefaultComparator;
@@ -27,11 +40,9 @@ private static JSONComparator getComparatorForMode(JSONCompareMode mode) {
* @param actualStr JSON string to compare
* @param comparator Comparator to use
* @return result of the comparison
- * @throws JSONException
* @throws IllegalArgumentException when type of expectedStr doesn't match the type of actualStr
*/
- public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
- throws JSONException {
+ public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator) {
Object expected = JSONParser.parseJSON(expectedStr);
Object actual = JSONParser.parseJSON(actualStr);
if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
@@ -58,10 +69,8 @@ else if (expected instanceof JSONObject) {
* @param actual actual json object
* @param comparator comparator to use
* @return result of the comparison
- * @throws JSONException
*/
- public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONComparator comparator)
- throws JSONException {
+ public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONComparator comparator) {
return comparator.compareJSON(expected, actual);
}
@@ -72,10 +81,8 @@ public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actu
* @param actual actual json array
* @param comparator comparator to use
* @return result of the comparison
- * @throws JSONException
*/
- public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONComparator comparator)
- throws JSONException {
+ public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONComparator comparator) {
return comparator.compareJSON(expected, actual);
}
@@ -85,6 +92,7 @@ public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual
*
* @param expected Expected {@code JSONstring}
* @param actual {@code JSONstring} to compare
+ * @return result of the comparison
*/
public static JSONCompareResult compareJson(final JSONString expected, final JSONString actual) {
final JSONCompareResult result = new JSONCompareResult();
@@ -102,10 +110,9 @@ public static JSONCompareResult compareJson(final JSONString expected, final JSO
* @param expectedStr Expected JSON string
* @param actualStr JSON string to compare
* @param mode Defines comparison behavior
- * @throws JSONException
+ * @return result of the comparison
*/
- public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONCompareMode mode)
- throws JSONException {
+ public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONCompareMode mode) {
return compareJSON(expectedStr, actualStr, getComparatorForMode(mode));
}
@@ -115,10 +122,9 @@ public static JSONCompareResult compareJSON(String expectedStr, String actualStr
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param mode Defines comparison behavior
- * @throws JSONException
+ * @return result of the comparison
*/
- public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONCompareMode mode)
- throws JSONException {
+ public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actual, JSONCompareMode mode) {
return compareJSON(expected, actual, getComparatorForMode(mode));
}
@@ -129,10 +135,9 @@ public static JSONCompareResult compareJSON(JSONObject expected, JSONObject actu
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param mode Defines comparison behavior
- * @throws JSONException
+ * @return result of the comparison
*/
- public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONCompareMode mode)
- throws JSONException {
+ public static JSONCompareResult compareJSON(JSONArray expected, JSONArray actual, JSONCompareMode mode) {
return compareJSON(expected, actual, getComparatorForMode(mode));
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/JSONCompareMode.java b/src/main/java/org/skyscreamer/jsonassert/JSONCompareMode.java
index a4df7e07..8185b065 100644
--- a/src/main/java/org/skyscreamer/jsonassert/JSONCompareMode.java
+++ b/src/main/java/org/skyscreamer/jsonassert/JSONCompareMode.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
/**
@@ -5,6 +19,9 @@
* Each mode encapsulates two underlying behaviors: extensibility and strict ordering.
*
*
+ *
+ * Behavior of JSONCompareMode
+ *
*
Extensible
Strict Ordering
*
STRICT
no
yes
*
LENIENT
yes
no
@@ -52,7 +69,7 @@ public enum JSONCompareMode {
private final boolean _extensible;
private final boolean _strictOrder;
- private JSONCompareMode(boolean extensible, boolean strictOrder) {
+ JSONCompareMode(boolean extensible, boolean strictOrder) {
_extensible = extensible;
_strictOrder = strictOrder;
}
@@ -76,6 +93,7 @@ public boolean hasStrictOrder() {
/**
* Get the equivalent {@code JSONCompareMode} with or without strict ordering.
*
+ * @param strictOrdering if true, requires strict ordering of array elements
* @return the equivalent {@code JSONCompareMode}
*/
public JSONCompareMode withStrictOrdering(boolean strictOrdering) {
@@ -89,6 +107,7 @@ public JSONCompareMode withStrictOrdering(boolean strictOrdering) {
/**
* Get the equivalent {@code JSONCompareMode} with or without extensibility.
*
+ * @param extensible if true, allows keys in actual that don't appear in expected
* @return the equivalent {@code JSONCompareMode}
*/
public JSONCompareMode withExtensible(boolean extensible) {
diff --git a/src/main/java/org/skyscreamer/jsonassert/JSONCompareResult.java b/src/main/java/org/skyscreamer/jsonassert/JSONCompareResult.java
index 2cf7cad9..55672099 100644
--- a/src/main/java/org/skyscreamer/jsonassert/JSONCompareResult.java
+++ b/src/main/java/org/skyscreamer/jsonassert/JSONCompareResult.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import java.util.ArrayList;
@@ -58,6 +72,7 @@ public String getMessage() {
/**
* Get the list of failures on field comparisons
+ * @return list of comparsion failures
*/
public List getFieldFailures() {
return Collections.unmodifiableList(_fieldFailures);
@@ -65,6 +80,7 @@ public List getFieldFailures() {
/**
* Get the list of missed on field comparisons
+ * @return list of comparsion failures
*/
public List getFieldMissing() {
return Collections.unmodifiableList(_fieldMissing);
@@ -72,6 +88,7 @@ public List getFieldMissing() {
/**
* Get the list of failures on field comparisons
+ * @return list of comparsion failures
*/
public List getFieldUnexpected() {
return Collections.unmodifiableList(_fieldUnexpected);
@@ -105,6 +122,7 @@ public Object getExpected() {
/**
* Check if comparison failed on any particular fields
+ * @return true if there are field failures
*/
public boolean isFailureOnField() {
return !_fieldFailures.isEmpty();
@@ -112,6 +130,7 @@ public boolean isFailureOnField() {
/**
* Check if comparison failed with missing on any particular fields
+ * @return true if an expected field is missing
*/
public boolean isMissingOnField() {
return !_fieldMissing.isEmpty();
@@ -119,6 +138,7 @@ public boolean isMissingOnField() {
/**
* Check if comparison failed with unexpected on any particular fields
+ * @return true if an unexpected field is in the result
*/
public boolean isUnexpectedOnField() {
return !_fieldUnexpected.isEmpty();
@@ -150,6 +170,7 @@ public void fail(String message) {
* @param field Which field failed
* @param expected Expected result
* @param actual Actual result
+ * @return result of comparision
*/
public JSONCompareResult fail(String field, Object expected, Object actual) {
_fieldFailures.add(new FieldComparisonFailure(field, expected, actual));
@@ -164,6 +185,7 @@ public JSONCompareResult fail(String field, Object expected, Object actual) {
* Identify that the comparison failed
* @param field Which field failed
* @param exception exception containing details of match failure
+ * @return result of comparision
*/
public JSONCompareResult fail(String field, ValueMatcherException exception) {
fail(field + ": " + exception.getMessage(), exception.getExpected(), exception.getActual());
@@ -179,6 +201,12 @@ private String formatFailureMessage(String field, Object expected, Object actual
+ "\n";
}
+ /**
+ * Identify the missing field
+ * @param field missing field
+ * @param expected expected result
+ * @return result of comparison
+ */
public JSONCompareResult missing(String field, Object expected) {
_fieldMissing.add(new FieldComparisonFailure(field, expected, null));
fail(formatMissing(field, expected));
@@ -192,16 +220,22 @@ private String formatMissing(String field, Object expected) {
+ "\n but none found\n";
}
- public JSONCompareResult unexpected(String field, Object value) {
- _fieldUnexpected.add(new FieldComparisonFailure(field, null, value));
- fail(formatUnexpected(field, value));
+ /**
+ * Identify unexpected field
+ * @param field unexpected field
+ * @param actual actual result
+ * @return result of comparison
+ */
+ public JSONCompareResult unexpected(String field, Object actual) {
+ _fieldUnexpected.add(new FieldComparisonFailure(field, null, actual));
+ fail(formatUnexpected(field, actual));
return this;
}
- private String formatUnexpected(String field, Object value) {
+ private String formatUnexpected(String field, Object actual) {
return field
+ "\nUnexpected: "
- + describe(value)
+ + describe(actual)
+ "\n";
}
@@ -211,7 +245,7 @@ private static String describe(Object value) {
} else if (value instanceof JSONObject) {
return "a JSON object";
} else {
- return value.toString();
+ return String.valueOf(value);
}
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/JSONParser.java b/src/main/java/org/skyscreamer/jsonassert/JSONParser.java
index 45df77c1..a70af96c 100644
--- a/src/main/java/org/skyscreamer/jsonassert/JSONParser.java
+++ b/src/main/java/org/skyscreamer/jsonassert/JSONParser.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import org.json.JSONArray;
@@ -22,9 +36,8 @@ private JSONParser() {}
*
* @param s Raw JSON string to be parsed
* @return JSONObject or JSONArray
- * @throws JSONException
*/
- public static Object parseJSON(final String s) throws JSONException {
+ public static Object parseJSON(final String s) {
if (s.trim().startsWith("{")) {
return new JSONObject(s);
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/LocationAwareValueMatcher.java b/src/main/java/org/skyscreamer/jsonassert/LocationAwareValueMatcher.java
index 56653cfa..cc2b7449 100644
--- a/src/main/java/org/skyscreamer/jsonassert/LocationAwareValueMatcher.java
+++ b/src/main/java/org/skyscreamer/jsonassert/LocationAwareValueMatcher.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
/**
*
*/
@@ -7,7 +21,7 @@
* A ValueMatcher extension that provides location in form of prefix to the equals method.
*
* @author Duncan Mackinder
- *
+ * @param Generic Type
*/
public interface LocationAwareValueMatcher extends ValueMatcher {
diff --git a/src/main/java/org/skyscreamer/jsonassert/RegularExpressionValueMatcher.java b/src/main/java/org/skyscreamer/jsonassert/RegularExpressionValueMatcher.java
index 7efb64eb..19a4ef1d 100644
--- a/src/main/java/org/skyscreamer/jsonassert/RegularExpressionValueMatcher.java
+++ b/src/main/java/org/skyscreamer/jsonassert/RegularExpressionValueMatcher.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
import java.util.regex.Pattern;
@@ -14,7 +28,7 @@
* specify regular expression pattern that actual value must match.
*
* @author Duncan Mackinder
- *
+ * @param Generic Type
*/
public class RegularExpressionValueMatcher implements ValueMatcher {
diff --git a/src/main/java/org/skyscreamer/jsonassert/ValueMatcher.java b/src/main/java/org/skyscreamer/jsonassert/ValueMatcher.java
index 58a86cf9..a05691a1 100644
--- a/src/main/java/org/skyscreamer/jsonassert/ValueMatcher.java
+++ b/src/main/java/org/skyscreamer/jsonassert/ValueMatcher.java
@@ -1,7 +1,33 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
+/**
+ * Represents a value matcher that can compare two objects for equality.
+ *
+ * @param the object type to compare
+ */
public interface ValueMatcher {
+ /**
+ * Compares the two provided objects whether they are equal.
+ *
+ * @param o1 the first object to check
+ * @param o2 the object to check the first against
+ * @return true if the objects are equal, false otherwise
+ */
boolean equal(T o1, T o2);
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/ValueMatcherException.java b/src/main/java/org/skyscreamer/jsonassert/ValueMatcherException.java
index 3639afce..19807722 100644
--- a/src/main/java/org/skyscreamer/jsonassert/ValueMatcherException.java
+++ b/src/main/java/org/skyscreamer/jsonassert/ValueMatcherException.java
@@ -1,3 +1,17 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert;
/**
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/AbstractComparator.java b/src/main/java/org/skyscreamer/jsonassert/comparator/AbstractComparator.java
index 037bb6af..190e47ea 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/AbstractComparator.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/AbstractComparator.java
@@ -1,7 +1,20 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONCompareResult;
@@ -11,19 +24,26 @@
/**
* This class provides a skeletal implementation of the {@link JSONComparator}
- * interface, to minimize the effort required to implement this interface.
+ * interface, to minimize the effort required to implement this interface.
+ *
+ *
*/
public abstract class AbstractComparator implements JSONComparator {
+ /**
+ * Default constructor
+ */
+ public AbstractComparator() {
+ }
+
/**
* Compares JSONObject provided to the expected JSONObject, and returns the results of the comparison.
*
* @param expected Expected JSONObject
* @param actual JSONObject to compare
- * @throws JSONException
*/
@Override
- public final JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException {
+ public final JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) {
JSONCompareResult result = new JSONCompareResult();
compareJSON("", expected, actual, result);
return result;
@@ -34,15 +54,20 @@ public final JSONCompareResult compareJSON(JSONObject expected, JSONObject actua
*
* @param expected Expected JSONArray
* @param actual JSONArray to compare
- * @throws JSONException
*/
@Override
- public final JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException {
+ public final JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) {
JSONCompareResult result = new JSONCompareResult();
compareJSONArray("", expected, actual, result);
return result;
}
+ /**
+ * @param prefix
+ * @param expected
+ * @param actual
+ * @param result
+ */
protected void checkJsonObjectKeysActualInExpected(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) {
Set actualKeys = getKeys(actual);
for (String key : actualKeys) {
@@ -52,7 +77,14 @@ protected void checkJsonObjectKeysActualInExpected(String prefix, JSONObject exp
}
}
- protected void checkJsonObjectKeysExpectedInActual(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException {
+ /**
+ *
+ * @param prefix
+ * @param expected
+ * @param actual
+ * @param result
+ */
+ protected void checkJsonObjectKeysExpectedInActual(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) {
Set expectedKeys = getKeys(expected);
for (String key : expectedKeys) {
Object expectedValue = expected.get(key);
@@ -65,7 +97,7 @@ protected void checkJsonObjectKeysExpectedInActual(String prefix, JSONObject exp
}
}
- protected void compareJSONArrayOfJsonObjects(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException {
+ protected void compareJSONArrayOfJsonObjects(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) {
String uniqueKey = findUniqueKey(expected);
if (uniqueKey == null || !isUsableAsUniqueKey(uniqueKey, actual)) {
// An expensive last resort
@@ -90,7 +122,7 @@ protected void compareJSONArrayOfJsonObjects(String key, JSONArray expected, JSO
}
}
- protected void compareJSONArrayOfSimpleValues(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException {
+ protected void compareJSONArrayOfSimpleValues(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) {
Map expectedCount = JSONCompareUtil.getCardinalityMap(jsonArrayToList(expected));
Map actualCount = JSONCompareUtil.getCardinalityMap(jsonArrayToList(actual));
for (Object o : expectedCount.keySet()) {
@@ -108,10 +140,10 @@ protected void compareJSONArrayOfSimpleValues(String key, JSONArray expected, JS
}
}
- protected void compareJSONArrayWithStrictOrder(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException {
+ protected void compareJSONArrayWithStrictOrder(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) {
for (int i = 0; i < expected.length(); ++i) {
- Object expectedValue = expected.get(i);
- Object actualValue = actual.get(i);
+ Object expectedValue = JSONCompareUtil.getObjectOrNull(expected, i);
+ Object actualValue = JSONCompareUtil.getObjectOrNull(actual, i);
compareValues(key + "[" + i + "]", expectedValue, actualValue, result);
}
}
@@ -121,13 +153,20 @@ protected void compareJSONArrayWithStrictOrder(String key, JSONArray expected, J
// This is expensive (O(n^2) -- yuck), but may be the only resort for some cases with loose array ordering, and no
// easy way to uniquely identify each element.
protected void recursivelyCompareJSONArray(String key, JSONArray expected, JSONArray actual,
- JSONCompareResult result) throws JSONException {
+ JSONCompareResult result) {
Set matched = new HashSet();
for (int i = 0; i < expected.length(); ++i) {
- Object expectedElement = expected.get(i);
+ Object expectedElement = JSONCompareUtil.getObjectOrNull(expected, i);
boolean matchFound = false;
for (int j = 0; j < actual.length(); ++j) {
- Object actualElement = actual.get(j);
+ Object actualElement = JSONCompareUtil.getObjectOrNull(actual, j);
+ if (expectedElement == actualElement) {
+ matchFound = true;
+ break;
+ }
+ if ((expectedElement == null && actualElement != null) || (expectedElement != null && actualElement == null)) {
+ continue;
+ }
if (matched.contains(j) || !actualElement.getClass().equals(expectedElement.getClass())) {
continue;
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/ArraySizeComparator.java b/src/main/java/org/skyscreamer/jsonassert/comparator/ArraySizeComparator.java
index e426cb8e..7e348b82 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/ArraySizeComparator.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/ArraySizeComparator.java
@@ -1,9 +1,22 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
import java.text.MessageFormat;
import org.json.JSONArray;
-import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
@@ -55,7 +68,7 @@ public ArraySizeComparator(JSONCompareMode mode) {
*/
@Override
public void compareJSONArray(String prefix, JSONArray expected,
- JSONArray actual, JSONCompareResult result) throws JSONException {
+ JSONArray actual, JSONCompareResult result) {
String arrayPrefix = prefix + "[]";
if (expected.length() < 1 || expected.length() > 2) {
result.fail(MessageFormat
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java b/src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
index 4adb2b69..73337bdf 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
@@ -1,6 +1,19 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
-import org.json.JSONException;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
@@ -19,7 +32,7 @@ public CustomComparator(JSONCompareMode mode, Customization... customizations)
}
@Override
- public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
+ public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) {
Customization customization = getCustomization(prefix);
if (customization != null) {
try {
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/DefaultComparator.java b/src/main/java/org/skyscreamer/jsonassert/comparator/DefaultComparator.java
index e2f6b57a..1e8efc01 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/DefaultComparator.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/DefaultComparator.java
@@ -1,7 +1,20 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
@@ -10,8 +23,8 @@
import static org.skyscreamer.jsonassert.comparator.JSONCompareUtil.allSimpleValues;
/**
- * This class is the default json comparator implementation.
- * Comparison is performed according to {@link JSONCompareMode} that is passed as constructor's argument.
+ * This class is the default json comparator implementation.
+ * Comparison is performed according to {@link JSONCompareMode} that is passed as constructor's argument.
*/
public class DefaultComparator extends AbstractComparator {
@@ -22,8 +35,7 @@ public DefaultComparator(JSONCompareMode mode) {
}
@Override
- public void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result)
- throws JSONException {
+ public void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) {
// Check that actual contains all the expected values
checkJsonObjectKeysExpectedInActual(prefix, expected, actual, result);
@@ -34,10 +46,14 @@ public void compareJSON(String prefix, JSONObject expected, JSONObject actual, J
}
@Override
- public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result)
- throws JSONException {
- if (expectedValue instanceof Number && actualValue instanceof Number) {
- if (((Number)expectedValue).doubleValue() != ((Number)actualValue).doubleValue()) {
+ public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) {
+ if (expectedValue == actualValue) {
+ return;
+ }
+ if (expectedValue == null || actualValue == null) {
+ result.fail(prefix, expectedValue, actualValue);
+ } else if (areNumbers(expectedValue, actualValue)) {
+ if (areNotSameDoubles(expectedValue, actualValue)) {
result.fail(prefix, expectedValue, actualValue);
}
} else if (expectedValue.getClass().isAssignableFrom(actualValue.getClass())) {
@@ -54,8 +70,7 @@ public void compareValues(String prefix, Object expectedValue, Object actualValu
}
@Override
- public void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result)
- throws JSONException {
+ public void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) {
if (expected.length() != actual.length()) {
result.fail(prefix + "[]: Expected " + expected.length() + " values but got " + actual.length());
return;
@@ -74,4 +89,12 @@ public void compareJSONArray(String prefix, JSONArray expected, JSONArray actual
recursivelyCompareJSONArray(prefix, expected, actual, result);
}
}
+
+ protected boolean areNumbers(Object expectedValue, Object actualValue) {
+ return expectedValue instanceof Number && actualValue instanceof Number;
+ }
+
+ protected boolean areNotSameDoubles(Object expectedValue, Object actualValue) {
+ return ((Number) expectedValue).doubleValue() != ((Number) actualValue).doubleValue();
+ }
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java b/src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
index b5b950fb..9a78d493 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
@@ -1,7 +1,20 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONCompareResult;
@@ -13,13 +26,54 @@
*/
public interface JSONComparator {
- JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
+ /**
+ * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
+ *
+ * @param expected the expected JSON object
+ * @param actual the actual JSON object
+ * @return the result of the comparison
+ */
+ JSONCompareResult compareJSON(JSONObject expected, JSONObject actual);
- JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
+ /**
+ * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
+ *
+ * @param expected the expected JSON array
+ * @param actual the actual JSON array
+ * @return the result of the comparison
+ */
+ JSONCompareResult compareJSON(JSONArray expected, JSONArray actual);
- void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
+ /**
+ * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
+ * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
+ *
+ * @param prefix the path in the json where the comparison happens
+ * @param expected the expected JSON object
+ * @param actual the actual JSON object
+ * @param result stores the actual state of the comparison result
+ */
+ void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result);
- void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
+ /**
+ * Compares two {@link Object}s on the provided path represented by {@code prefix} and
+ * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
+ *
+ * @param prefix the path in the json where the comparison happens
+ * @param expectedValue the expected value
+ * @param actualValue the actual value
+ * @param result stores the actual state of the comparison result
+ */
+ void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result);
- void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
+ /**
+ * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
+ * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
+ *
+ * @param prefix the path in the json where the comparison happens
+ * @param expected the expected JSON array
+ * @param actual the actual JSON array
+ * @param result stores the actual state of the comparison result
+ */
+ void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result);
}
diff --git a/src/main/java/org/skyscreamer/jsonassert/comparator/JSONCompareUtil.java b/src/main/java/org/skyscreamer/jsonassert/comparator/JSONCompareUtil.java
index 6d28dd97..8a7fe18d 100644
--- a/src/main/java/org/skyscreamer/jsonassert/comparator/JSONCompareUtil.java
+++ b/src/main/java/org/skyscreamer/jsonassert/comparator/JSONCompareUtil.java
@@ -1,34 +1,69 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
package org.skyscreamer.jsonassert.comparator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
-import java.util.*;
-
/**
- * Utility class that contains Json manipulation methods
+ * Utility class that contains Json manipulation methods.
*/
public final class JSONCompareUtil {
private static Integer INTEGER_ONE = new Integer(1);
- private JSONCompareUtil() {}
+ private JSONCompareUtil() {
+ }
- public static Map arrayOfJsonObjectToMap(JSONArray array, String uniqueKey) throws JSONException {
+ /**
+ * Converts the provided {@link JSONArray} to a Map of {@link JSONObject}s where the key of each object
+ * is the value at {@code uniqueKey} in each object.
+ *
+ * @param array the JSON array to convert
+ * @param uniqueKey the key to map the JSON objects to
+ * @return the map of {@link JSONObject}s from {@code array}
+ */
+ public static Map arrayOfJsonObjectToMap(JSONArray array, String uniqueKey) {
Map valueMap = new HashMap();
- for(int i = 0 ; i < array.length() ; ++i) {
- JSONObject jsonObject = (JSONObject)array.get(i);
+ for (int i = 0; i < array.length(); ++i) {
+ JSONObject jsonObject = (JSONObject) array.get(i);
Object id = jsonObject.get(uniqueKey);
valueMap.put(id, jsonObject);
}
return valueMap;
}
-
- public static String findUniqueKey(JSONArray expected) throws JSONException {
+ /**
+ * Searches for the unique key of the {@code expected} JSON array.
+ *
+ * @param expected the array to find the unique key of
+ * @return the unique key if there's any, otherwise null
+ */
+ public static String findUniqueKey(JSONArray expected) {
// Find a unique key for the object (id, name, whatever)
- JSONObject o = (JSONObject)expected.get(0); // There's at least one at this point
- for(String candidate : getKeys(o)) {
+ JSONObject o = (JSONObject) expected.get(0); // There's at least one at this point
+ for (String candidate : getKeys(o)) {
if (isUsableAsUniqueKey(candidate, expected)) return candidate;
}
// No usable unique key :-(
@@ -36,12 +71,22 @@ public static String findUniqueKey(JSONArray expected) throws JSONException {
}
/**
- * {@code candidate} is usable as a unique key if every element in the
- * {@code array} is a JSONObject having that key, and no two values are the same.
+ *
Looks to see if candidate field is a possible unique key across a array of objects.
+ * Returns true IFF:
+ *
+ *
array is an array of JSONObject
+ *
candidate is a top-level field in each of of the objects in the array
+ *
candidate is a simple value (not JSONObject or JSONArray)
+ *
candidate is unique across all elements in the array
+ *
+ *
+ * @param candidate is usable as a unique key if every element in the
+ * @param array is a JSONObject having that key, and no two values are the same.
+ * @return true if the candidate can work as a unique id across array
*/
- public static boolean isUsableAsUniqueKey(String candidate, JSONArray array) throws JSONException {
+ public static boolean isUsableAsUniqueKey(String candidate, JSONArray array) {
Set seenValues = new HashSet();
- for (int i = 0 ; i < array.length() ; i++) {
+ for (int i = 0; i < array.length(); i++) {
Object item = array.get(i);
if (item instanceof JSONObject) {
JSONObject o = (JSONObject) item;
@@ -62,29 +107,65 @@ public static boolean isUsableAsUniqueKey(String candidate, JSONArray array) thr
return true;
}
- public static List jsonArrayToList(JSONArray expected) throws JSONException {
+ /**
+ * Converts the given {@link JSONArray} to a list of {@link Object}s.
+ *
+ * @param expected the JSON array to convert
+ * @return the list of objects from the {@code expected} array
+ */
+ public static List jsonArrayToList(JSONArray expected) {
List jsonObjects = new ArrayList(expected.length());
- for(int i = 0 ; i < expected.length() ; ++i) {
- jsonObjects.add(expected.get(i));
+ for (int i = 0; i < expected.length(); ++i) {
+ jsonObjects.add(getObjectOrNull(expected, i));
}
return jsonObjects;
}
- public static boolean allSimpleValues(JSONArray array) throws JSONException {
- for(int i = 0 ; i < array.length() ; ++i) {
- if (!isSimpleValue(array.get(i))) {
+ /**
+ * Returns the value present in the given index position. If null value is present, it will return null
+ *
+ * @param jsonArray the JSON array to get value from
+ * @param index index of object to retrieve
+ * @return value at the given index position
+ */
+ public static Object getObjectOrNull(JSONArray jsonArray, int index) {
+ return jsonArray.isNull(index) ? null : jsonArray.get(index);
+ }
+
+ /**
+ * Returns whether all of the elements in the given array are simple values.
+ *
+ * @param array the JSON array to iterate through on
+ * @return true if all the elements in {@code array} are simple values
+ * @see #isSimpleValue(Object)
+ */
+ public static boolean allSimpleValues(JSONArray array) {
+ for (int i = 0; i < array.length(); ++i) {
+ if (!array.isNull(i) && !isSimpleValue(array.get(i))) {
return false;
}
}
return true;
}
+ /**
+ * Returns whether the given object is a simple value: not {@link JSONObject} and not {@link JSONArray}.
+ *
+ * @param o the object to inspect
+ * @return true if {@code o} is a simple value
+ */
public static boolean isSimpleValue(Object o) {
return !(o instanceof JSONObject) && !(o instanceof JSONArray);
}
- public static boolean allJSONObjects(JSONArray array) throws JSONException {
- for(int i = 0 ; i < array.length() ; ++i) {
+ /**
+ * Returns whether all elements in {@code array} are {@link JSONObject} instances.
+ *
+ * @param array the array to inspect
+ * @return true if all the elements in the given array are JSONObjects
+ */
+ public static boolean allJSONObjects(JSONArray array) {
+ for (int i = 0; i < array.length(); ++i) {
if (!(array.get(i) instanceof JSONObject)) {
return false;
}
@@ -92,8 +173,14 @@ public static boolean allJSONObjects(JSONArray array) throws JSONException {
return true;
}
- public static boolean allJSONArrays(JSONArray array) throws JSONException {
- for(int i = 0 ; i < array.length() ; ++i) {
+ /**
+ * Returns whether all elements in {@code array} are {@link JSONArray} instances.
+ *
+ * @param array the array to inspect
+ * @return true if all the elements in the given array are JSONArrays
+ */
+ public static boolean allJSONArrays(JSONArray array) {
+ for (int i = 0; i < array.length(); ++i) {
if (!(array.get(i) instanceof JSONArray)) {
return false;
}
@@ -101,11 +188,17 @@ public static boolean allJSONArrays(JSONArray array) throws JSONException {
return true;
}
+ /**
+ * Collects all keys in {@code jsonObject}.
+ *
+ * @param jsonObject the {@link JSONObject} to get the keys of
+ * @return the set of keys
+ */
public static Set getKeys(JSONObject jsonObject) {
Set keys = new TreeSet();
Iterator> iter = jsonObject.keys();
- while(iter.hasNext()) {
- keys.add((String)iter.next());
+ while (iter.hasNext()) {
+ keys.add((String) iter.next());
}
return keys;
}
@@ -118,6 +211,13 @@ public static String formatUniqueKey(String key, String uniqueKey, Object value)
return key + "[" + uniqueKey + "=" + value + "]";
}
+ /**
+ * Creates a cardinality map from {@code coll}.
+ *
+ * @param coll the collection of items to convert
+ * @param the type of elements in the input collection
+ * @return the cardinality map
+ */
public static Map getCardinalityMap(final Collection coll) {
Map count = new HashMap();
for (T item : coll) {
diff --git a/src/site/resources/cookbook.html b/src/site/resources/cookbook.html
index 0ca0eb7a..2e271348 100644
--- a/src/site/resources/cookbook.html
+++ b/src/site/resources/cookbook.html
@@ -132,6 +132,6 @@