How to count members with jsonpath?

Is it possible to count the number of members using JsonPath?

Using Spring MVC test I'm testing a controller that generates

{"foo": "oof", "bar": "rab"}


standaloneSetup(new FooController(fooService)).build()

I'd like to make sure that no other members are present in the generated json. Hopefully by counting them using jsonPath. Is it possible? Alternate solutions are welcome too.


  • To test size of array: jsonPath("$", hasSize(4))

    To count members of object: jsonPath("$.*", hasSize(4))

    I.e. to test that API returns an array of 4 items:

    accepted value: [1,2,3,4]

           .andExpect(jsonPath("$", hasSize(4)));

    to test that API returns an object containing 2 members:

    accepted value: {"foo": "oof", "bar": "rab"}

           .andExpect(jsonPath("$.*", hasSize(2)));

    I'm using Hamcrest version 1.3 and Spring Test 3.2.5.RELEASE

    hasSize(int) javadoc

    Note: You need to include hamcrest-library dependency and import static org.hamcrest.Matchers.*; for hasSize() to work.