Search code examples
rest-assuredrest-assured-jsonpath

Rest Assured - Json Extract


I am receiving response in the following structure:

[{
    "builds": [{
            "description": "JP MORGAN",
            "land": "FU",
            "companyCode": "1234",
            "accountNumber": "00000000000",
            "shortID4": "XYS"
        }
    ]
}

]

Whenever I want to extract JSON property, e.g. description, the final object is not as I expect. It creates List having ArrayString.

List<String> values = resp.path("builds.description");

Whenever I want to test/print it is not simply possible because of the structure. enter image description here

How to get the value from this JSON object to simple List which would be containing the values? Thanks


Solution

  • Hope below one of the solutions can fix your problem. I recommend you to use first one.

    String responseJson= "[{     \"builds\": [{             \"description\": \"JP MORGAN\",         },      {             \"description\": \"JP MORGAN\",         }     ] }]";
    JsonPath jp = new JsonPath(responseJson);
    List<String> singleDestList = jp.getList("builds[0].description");
    System.out.println(singleDestList);
    

    OR

    List<List<List<String>>> descriptionsList =jp.get("builds.description");
    List<Object> flatList = descriptionsList.stream().flatMap(List::stream).collect(Collectors.toList());       
    System.out.println(flatList.toString());
    

    OR

    String[] descriptionArray = jp.get("builds.description").toString().replaceAll("\\[", "").replaceAll("]", "").split(",");
    List<String> descriptionList = Arrays.asList(descriptionArray);
    System.out.println(descriptionList);