Search code examples
serenity-bddrest-assured-jsonpath

How to fetch the particular field value from response body


This is the response body of post method

"body":
{
  "id": 538,
  "Fname": "abc",
  "Lname": "Xyz",
  "Type": {
    "Type": "tryrtyr",
    "createdBy": "ytyryr",
    "createdDate": "2022-07-22T09:24:37.616+00:00",
    "lastModifiedBy": "rtyryry",
    "lastModifiedDate": "2022-07-22T09:24:37.616+00:00"
  }
}

I tried to fetch the Id value but it is showing null value. Fname, Lname are passing from excel file.

String jsonString = response.asString();
jsonString = response.asString();
List<Map<String, Object>> body = JsonPath.from(jsonString).get("");
Object Id = null;
for (Map<String, Object> item: body) {
    if (item.get("Fname").toString().equals(Fname) &&
        item.get("Lname").toString().equals(Lname)); {
        Id = Integer.parseInt(item.get("id").toString());
    }
}
System.out.println(Id);

Solution

  • Since the body is json object, not array, so you don't need a List here. I think you just need.

    int id = response.jsonpath().getInt("id");