How to search/find In JSON with java

You can also use the JsonPath project provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Examples:

To get a list of all book categories:

List<String> categories = JsonPath.from(json).get("store.book.category");

Get the first book category:

String category = JsonPath.from(json).get("store.book[0].category");

Get the last book category:

String category = JsonPath.from(json).get("store.book[-1].category");

Get all books with price between 5 and 15:

List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");

GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.

Leave a Comment