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.


Firstly, add json-path dependency in pom

<dependency>
     <groupId>com.jayway.jsonpath</groupId>
     <artifactId>json-path</artifactId>
     <version>2.2.0</version>
</dependency>

Create a utility in Base Class that can be reused :

 public static String getValueFromJsonPath(String apiResponse, String jsonPath) {
        return JsonPath.read(apiResponse, jsonPath);
    }

One example of using this method :

getValueFromJsonPath(apiResponse, "$.store.book[0].category");

NOTE : Create overloaded method with different return types depending upon the expected result (like List for fetching a list from json)