How to search/find In JSON with java

Ssire picture Ssire · Mar 11, 2015 · Viewed 21k times · Source

I have a below JSON string from the below i want to find/search criteria in JSON String.

1). To find the Number of keys present. 2). To get the values of given key(if we have array)

{
"store": {
    "book": [
        {
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
        },
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        },
        {
            "category": "fiction",
            "author": "J. R. R. Tolkien",
            "title": "The Lord of the Rings",
            "isbn": "0-395-19395-8",
            "price": 22.99
        }
    ],
    "bicycle": {
        "color": "red",
        "price": 19.95
    }
},
 "expensive": 10
}

I am looking a solution like Groovy GPath Syntax

  • store.book - size of this array.
  • store.book[*].category - how may times the key present in the array.
  • store.bicycle - if it found it has to return true value

Answer

Johan picture Johan · Mar 16, 2015

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.