Reputation: 1409
I'm getting response this way:
Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json")
.when().post("/admin");
String responseBody = response.getBody().asString();
I have a json in responseBody:
{"user_id":39}
Could I extract to string using rest-assured's method only this value = 39?
Upvotes: 59
Views: 164887
Reputation: 33
you can directly use the response object as well.
Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json").when().post("/admin");
String userId = response.path("user_id").toString();
Upvotes: 1
Reputation: 1842
To serialize the response into a class, define the target class
public class Result {
public Long user_id;
}
And map response to it:
Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);
You must have Jackson or Gson in the classpath as stated in the documentation.
Upvotes: 13
Reputation: 566
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
Upvotes: -2
Reputation: 5482
There are several ways. I personally use the following ones:
extracting single value:
String user_Id =
given().
when().
then().
extract().
path("user_id");
work with the entire response when you need more than one:
Response response =
given().
when().
then().
extract().
response();
String userId = response.path("user_id");
extract one using the JsonPath to get the right type:
long userId =
given().
when().
then().
extract().
jsonPath().getLong("user_id");
Last one is really useful when you want to match against the value and the type i.e.
assertThat(
when().
then().
extract().
jsonPath().getLong("user_id"), equalTo(USER_ID)
);
The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage
Upvotes: 28
Reputation: 40618
You can also do like this if you're only interested in extracting the "user_id":
String userId =
given().
contentType("application/json").
body(requestBody).
when().
post("/admin").
then().
statusCode(200).
extract().
path("user_id");
In its simplest form it looks like this:
String userId = get("/person").path("person.userId");
Upvotes: 51