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?
We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute. We shall first send a GET request via Postman on a mock API URL and observe the Response body.
To extract the scalar value from the JSON string, use the json_extract_scalar function. It is similar to json_extract , but returns only scalar values (Boolean, number, or string).
Syntax: String json = " json response from server"; List<String> result = JsonPath. read(json, "JsonPath Locator"); A simple example of parsing the JSON response using JSONPath with rest assured.
json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With