Test JSON with a few lines of code

JSONassert helps you writing JSON unit tests

You have to write a unit test and JSON is involved. Usually this will end up in a lot of lines of code. You know the situation, I bet.

Here JSONassert comes into play. It allows to write JSON unit tests with just a few lines of code. For example checking an JSON object:

  book = new Book();
  book.setName("The book");

  String result = BookUtils.toJson(book);
  boolean strict = false;
  JSONAssert.assertEquals("{\"name\":\"The book\"}", result, strict);

The strictMode == false makes ordering not relevant and makes your test less brittle.

JSONassert comes with JSONCompareResult. I thinks this class is very handy when you are interested in a particular aspect like a missing field or value.

  JSONCompareResult result =
    JSONCompare.compareJSON("{\"name\":\"The book\",\"pages\":100}",
        "{\"name\":\"The book\"}", JSONCompareMode.LENIENT);
  assertEquals(result.getFieldMissing().size(), 1);
  FieldComparisonFailure fieldComparisonFailure = result.getFieldMissing().get(0);

JSONCompareResult provides a list of missing fields and fields with errors. Depending on your case, you can easily determine which field makes trouble.

JSONassert is a real cool third library. I like it!

GitHub-Mark-32px On Github you find more examples.