繁体   English   中英

放心。 是否可以从请求 json 中提取值?

[英]Rest-assured. Is it possible to extract value from request json?

我得到这样的回应:

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 吗?

如果您只对提取“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");

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

提取单个值:

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

我找到了答案:)

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

就我而言:

JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");

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

public class Result {
    public Long user_id;
}

并映射对它的响应:

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

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

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

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

String userId = response.path("user_id").toString();
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM