If you are already using JUnit, the latest version now employs Hamcrest. It is a generic matching framework (especially useful for unit testing) that can be extended to build new matchers.
There is a small open source library called hamcrest-json
with JSON-aware matches. It is well documented, tested, and supported. Below are some useful links:
Example code using objects from the JSON library org.json.simple
:
Assert.assertThat(
jsonObject1.toJSONString(),
SameJSONAs.sameJSONAs(jsonObject2.toJSONString()));
Optionally, you may (1) allow "any-order" arrays and (2) ignore extra fields.
Since there are a variety of JSON libraries for Java (Jackson
, GSON
, json-lib
, etc.), it is useful that hamcrest-json
supports JSON text (as java.lang.String
), as well as natively supporting objects from Douglas Crockford's JSON library org.json
.
Finally, if you are not using JUnit, you can use Hamcrest directly for assertions. (I wrote about it here.)