Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Jackson Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

In this quick tutorial, we'll explore how to use JsonPath to count objects and arrays in a JSON document.

JsonPath provides a standard mechanism to traverse through specific parts of a JSON document. We can say JsonPath is to JSON what XPath is to XML.

2. Required Dependencies

We're using the following JsonPath Maven dependency, which is, of course, available on Maven Central:


3. Sample JSON

The following JSON will be used to illustrate the examples:

                "author":"Arthur Conan Doyle",
                "title":"Sherlock Holmes",
                "author":"J. R. R. Tolkien",
                "title":"The Lord of the Rings",

4. Count JSON Objects

The root element is denoted by the Dollar symbol “$”. In the following JUnit test, we call JsonPath.read() with the JSON String and the JSON path “$” that we want to count:

public void shouldMatchCountOfObjects() {
    Map<String, String> objectMap = JsonPath.read(json, "$");
    assertEquals(3, objectMap.keySet().size());

By counting the size of the resulting Map, we know how many elements are at the given path within the JSON structure.

5. Count JSON Array Size

In the following JUnit test, we query the JSON to find the array containing all books under the items element:

public void shouldMatchCountOfArrays() {
    JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
    assertEquals(2, jsonArray.size());

6. Conclusion

In this article, we've covered some basic examples on how to count items within a JSON structure.

You can explore more path examples in the official JsonPath docs.

As always, the code examples can be found in the GitHub repository.

Jackson bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!