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?
This question is related to
java
json
rest
rest-assured
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
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
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");
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 the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)
Source: Stackoverflow.com