Reputation: 1863
I need to obtain two values from JSON response data returned from a Rest Assured modelled request:
public void getCustomerStatuses() {
Response response =
given().header("X-AC-User-ID","test-user").
spec(customerApiSpec).
when().
get("/api/v6/status/" + ref + "/").
then().
assertThat().statusCode(200).extract().response();
custStatusId = response.path("$.cust[?(@.name=='STATUS_ID')].id");
custRenewalId = response.path("$.cust[?(@.name=='RENEWAL_ID')].id");
System.out.println(custStatusId);
System.out.println(custRenewalId);
}
This throws and java.lang.IllegalArgumentException: Invalid JSON expression:Script1.groovy: 1: Unexpected input: '$.cust[?' @ line 1, column 36. $.cust[?(@.name=='STATUS_ID')].id
What is the correct, best way of obtaining these? I'm aware I can chain extract().response().jsonPath();
off the request but not sure how I can obtain >1 value
Upvotes: 1
Views: 2502
Reputation: 803
Yes you can use JsonPath
Response response =
given().header("X-AC-User-ID","test-user").
spec(customerApiSpec).
when().
get("/api/v6/status/" + ref + "/").
then().
assertThat().statusCode(200).extract().response();
JsonPath jsonPath = response.jsonPath();
If the received json body is this;
{
"value1":{
"id": 1,
"abc": {
"v1": "o1",
"v2": "o2"
}
},
"value2":{
"id": 2,
"title": "test2"
}
}
Then use the get(String path)
method;
String v1 = jsonPath.get("value1.abc.v1"); // o1
String title = jsonPath.get("value2.title"); // test2
Required import;
io.restassured.path.json.JsonPath;
Upvotes: 4