RestAssured:如何提取 JSON 数组中的字段
RestAssured: how to extract field inside JSON array
我知道有人发布了 ,但是答案对我不起作用。
我正在使用 RestAssured。如何将我的 Response
转换为 JSON 对象,然后提取 JSON 数组中的字段(在我的例子中,在 errors
数组中)?
Response response =
given().
contentType(ContentType.JSON).
body(jsonAsMap).
when().
post("/customers").
then().
statusCode(400).extract().response();
//get "code" field inside "errors".
在 Postman 中测试请求时,我得到了这个结果:
{
"uri": "/customers/",
"query": null,
"method": "POST",
"contentType": "application/json",
"status": 400,
"statusMessage": "Bad Request",
"errors": [
{
"field": "firstName",
"code": "firstName.required", //need to extract this field
"message": "firstName is required"
}
]
}
实现此目标的最简单方法是什么?
您可以使用 JsonPath 访问值并将其转换为 Java 类型。
像这样:
String errorCode = ...then().extract().jsonPath().getString( "errors[0].code" )
除了上述答案之外,还有一个替代解决方案:
String errCode = ...then().extract().path("errors[0].code");
我知道有人发布了
我正在使用 RestAssured。如何将我的 Response
转换为 JSON 对象,然后提取 JSON 数组中的字段(在我的例子中,在 errors
数组中)?
Response response =
given().
contentType(ContentType.JSON).
body(jsonAsMap).
when().
post("/customers").
then().
statusCode(400).extract().response();
//get "code" field inside "errors".
在 Postman 中测试请求时,我得到了这个结果:
{
"uri": "/customers/",
"query": null,
"method": "POST",
"contentType": "application/json",
"status": 400,
"statusMessage": "Bad Request",
"errors": [
{
"field": "firstName",
"code": "firstName.required", //need to extract this field
"message": "firstName is required"
}
]
}
实现此目标的最简单方法是什么?
您可以使用 JsonPath 访问值并将其转换为 Java 类型。
像这样:
String errorCode = ...then().extract().jsonPath().getString( "errors[0].code" )
除了上述答案之外,还有一个替代解决方案:
String errCode = ...then().extract().path("errors[0].code");