52

我得到这样的回应:

Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json")
.when().post("/admin");
String responseBody = response.getBody().asString();

我在 responseBody 中有一个 json:

{"user_id":39}

我可以使用放心的方法提取到字符串,只有这个值 = 39?

4

6 回答 6

48

如果您只对提取“user_id”感兴趣,也可以这样做:

String userId = 
given().
        contentType("application/json").
        body(requestBody).
when().
        post("/admin").
then().
        statusCode(200).
extract().
        path("user_id");

在最简单的形式中,它看起来像这样:

String userId = get("/person").path("person.userId");
于 2014-01-22T10:13:26.740 回答
24

我找到了答案:)

使用JsonPathXmlPath(如果您有 XML)从响应正文中获取数据。

就我而言:

JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");
于 2014-01-17T09:53:57.087 回答
23

有几种方法。我个人使用以下几种:

提取单个值:

String user_Id =
given().
when().
then().
extract().
        path("user_id");

当您需要多个响应时,使用整个响应:

Response response =
given().
when().
then().
extract().
        response();

String userId = response.path("user_id");

使用 JsonPath 提取一个以获得正确的类型:

long userId =
given().
when().
then().
extract().
        jsonPath().getLong("user_id");

当你想匹配值和类型时,最后一个非常有用,即

assertThat(
    when().
    then().
    extract().
            jsonPath().getLong("user_id"), equalTo(USER_ID)
);

放心的文档非常具有描述性和完整。有很多方法可以实现您的要求:https ://github.com/jayway/rest-assured/wiki/Usage

于 2015-11-23T11:25:16.577 回答
11

要将响应序列化为一个类,请定义目标类

public class Result {
    public Long user_id;
}

并映射对它的响应:

Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);

如文档中所述,您必须在类路径中包含 Jackson 或 Gson 。

于 2015-05-12T12:54:56.773 回答
0

您也可以直接使用响应对象。

Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json").when().post("/admin");

String userId = response.path("user_id").toString();
于 2021-11-12T06:14:11.117 回答
-2
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
于 2018-09-21T15:40:00.160 回答