我正在尝试返回值“ Welcome!”。其中对象包含等于“主题”的“名称”键。响应正文数据如下:
"payload": {
"mimeType": "multipart/alternative",
"headers": [
{
"name": "Mime-Version",
"value": "1.0"
},
{
"name": "Subject",
"value": "Welcome!"
},
{
"name": "To",
"value": "Jane Doe <xyz@xyz.com>"
},
{
"name": "Message-ID",
"value": "<123456.abc.com>"
}
以下代码段将返回遇到的第一个“值”:“ 1.0”,但我需要在name =“ Subject”的情况下获取该值。如何过滤结果并检查匹配的字符串?
Response response = SerenityRest.rest()
.contentType("application/json")
.get("URL")
response.then().statusCode(200);
String subject = response.jsonPath().getString("payload.headers.value");
“ Welcome”值不是静态的,但“ name”:“ Subject”将永远不变。
答案 0 :(得分:1)
我不确定您的问题是什么,如果您正在寻找一个jsonpath过滤器来获取与字段"name": "Subject"
关联的值,那么这通常应该可以工作:
"payload.headers[?(@.name=='Subject')].value"
但是我看一下json-path rest-assured,它是Serenity rest用来执行json-path操作的库,该库不使用标准的json-path合奏,而是基于groovy lambda的合奏来执行高级搜索。所以这应该工作:
"headers.find{ it.name == 'Subject' }.value"
我用一个完整的例子进行测试:
JsonPath.from("{\"payload\": {\n" +
" \"mimeType\": \"multipart/alternative\",\n" +
" \"headers\": [\n" +
" {\n" +
" \"name\": \"Mime-Version\",\n" +
" \"value\": \"1.0\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Subject\",\n" +
" \"value\": \"Welcome!\"\n" +
" },\n" +
" {\n" +
" \"name\": \"To\",\n" +
" \"value\": \"Jane Doe <xyz@xyz.com>\"\n" +
" },\n" +
" {\n" +
" \"name\": \"Message-ID\",\n" +
" \"value\": \"<123456.abc.com>\"\n" +
" }\n" +
" ]\n" +
"}}")
.getString("headers.find{ it.name == 'Subject' }.value");
// returns "Welcome!"
此博客可帮助我了解合酶的变化: What's new in REST Assured 1.8?