1
{
   "users":[
      {
         "customerId":"2kXE3upOg5hnOG",
         "ccoId":"paalle",
         "userGroups":[
            "CX Cloud Super Admins",
            "CX Cloud Admins",
            "aAutoGroupMarked12"
         ],
         "emailId":"paalle@test.com",
         "fullName":"Pavan Alle",
         "isSelected":true
      },
      {
         "customerId":"2kXE3upOg5hnOG",
         "ccoId":"rtejanak",
         "userGroups":[
            "aTestUserGroupname1234"
         ],
         "emailId":"rtejanak@test.com",
         "fullName":"Raja Ravi Teja Nakirikanti"
      }
   ],
   "pagination":{
      "pageNumber":1,
      "totalPages":2,
      "rowPerPage":10,
      "totalRows":11
   }
}

This is my JSON, where is want to extract ccoId, if and only if the userGroups have a group name as aAutoGroupMarked12. I am new to API automation and JsonPath. In my company, we were told to use io.rest-assured API's JsonPath class. can someone please give me suggestions on how should I write a path which returns me ccoId value

Fenio
  • 3,528
  • 1
  • 13
  • 27
Rajaji
  • 133
  • 2
  • 14

1 Answers1

0

I would use POJO to filter out the reults based on userGroups field. POJO is a Java class representing JSON. Your JSON can be transformed into:

public class UserEntity {
    public String customerId;
    public String ccoId;
    public List<String> userGroups;
    public String emailId;
    public String fullName;
    public Boolean isSelected;
}

Each of the variable names need to be exactly like the names in the JSON.

Now, below line transforms JSON into List<UserEntity> so we transform JSON to Java classes

JsonPath jsonPath = JsonPath.from("json String or File");
UserEntity[] userEntities = jsonPath.getObject("$.users", UserEntity[].class);

We tell Rest-Assured's Json Path to look for users element in JSON. It's a list so we transform it into an Array, then we can also change it to list and iterate.

List<UserEntity> usersList = List.of(userEntities);

It will make it much easier to operate on. I would recommend using Streams but we'll use regular foreach in this case:

public void String getCcoId(List<UserEntity> usersList) {
    for (UserEntity user : usersList) {
        List<String> userGroups = user.userGroups;
        for (String userGroup : userGroups) {
            if (userGroup.equals("aAutoGroupMarked12")) {
                return user.ccoId;
            }
        }
    }
}

The code above looks for particular userGroup and if it matches first occurrence it returns ccoId

Fenio
  • 3,528
  • 1
  • 13
  • 27
  • HI thnaks for your response, but i dont want to use this process because its a one time activity, and creating a class for this is heavy for me. Is there any option similar to contains(from java)? or any other way I can do this? Please help – Rajaji Aug 23 '20 at 13:07