Home Ask Login Register

Developers Planet

Your answer is one click away!

Abhishek Singh February 2016

Get List by using Jsonpath

I am using Jayway JsonPath 2.1.0 to parse a JSON String using JsonPath.

The JSON Structure is as follows:

    "status": "",
    "source": "",
    "processedRecords": 1,
    "totalRecords": 4,
    "description": "1 company(ies) added/updated, and 2 company(ies) failed",
    "payload": [{
        "Added/updated company(ies)": [
    }, {
        "Failed company(ies)": [{
            "id": "COM003FILE",
            "index": "NA",
            "errorMsg": [
        }, {
            "id": "COM002FILE",
            "index": "NA",
            "errorMsg": [

Now the requirement is to get a list of ids whose errorMsg contains INACTIVE. to achieve this I am using filters as shown below.

Filter resposneFilter = Filter.filter(Criteria.where("errorMsg").is(
List<Map<String, Object>> respons = JsonPath.parse(response).read(
            "$.payload[*]", resposneFilter);

but as output I am getting all the values in payload.

Is it possible to get the expected results?


Raf February 2016

Taking into account the JSON you provided and reading through the documentation of Jayway JsonPath. I found two solution that could help resolve you issue.

  1. Solution 1 allows you to directly access the errorMsg field but, not applicbable when there are more than one companies as you have to manually loop
  2. Solution 2 allows constructions of a Custom predicate that is specific to your case and is somewhat generic.

Solution 1 The filter that you have seem to be correct, as shown below:

Filter responseFilter = Filter.filter(Criteria.where("errorMsg").is("INACTIVE"));

Looking into your JSON, payload can be thought of as starting point and the structure seem to be fixed the second value of payload array is failed companies and that is what you are interested in hence, I would write the json path as follow:

Map<String, Object> inactiveFailedCompany =  
           parse(json).read("$.payload[1].['Failed company(ies)'][1]", responseFilter);

If you notice above, I have specified payload[1] and I assume that is how your JSON is structured. I have also specified ['Failed company(ies)'][1] and that is to access the company that has INACTIVE. You can obviously use this solution with a loop to loop through index of ['Failed company(ies)'][1] and print the ID as follow:

System.out.println("Company Object > " + inactiveFailedCompany.toString());
//output: Output > {id=COM002FILE, index=NA, errorMsg=[["INACTIVE"],["INVALID_LOCATION","INACTIVE"]]}

System.out.println("Company ID > " + inactiveFailedCompany.get("id"));
//output: COM002FILE

Looking at the above solution, I felt bad because it is not good enough, so I read more in the documentation and came across Roll your

Post Status

Asked in February 2016
Viewed 2,952 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life