通过 RestAssured 中的 JsonPath 访问匿名数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13803316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access elements of an anonymous array via JsonPath in RestAssured
提问by Heiko Rupp
I have an anonymous array in JSON returned from a service like:
我有一个从服务返回的 JSON 匿名数组,例如:
[
{"foo":1, "bar":2 , "baz":3 },
{"foo":3, "bar":4 , "baz":5 }
]
How can I access the barelements e.g. in
我如何访问bar元素,例如
expect().body("$[*].bar", hasItems(2,4))
I tried a few possibilities that I found here and also on the JsonPath pageby Stefan G?ssner, but whatever I try I get exceptions. My issue seems to directly come from trying to access that list of items.
我尝试了一些在此处以及Stefan G?ssner的JsonPath 页面上找到的可能性,但是无论我尝试什么,我都会遇到异常。我的问题似乎直接来自尝试访问该项目列表。
回答by Johan
Given that you have:
鉴于您有:
[
{"foo":1, "bar":2 , "baz":3 },
{"foo":3, "bar":4 , "baz":5 }
]
You can do the following in Rest Assured:
您可以在 Rest Assured 中执行以下操作:
then().body("bar",hasItems(2,4))
or
或者
expect().body("bar",hasItems(2,4))
if you're using the legacy API.
如果您使用的是旧版 API。
回答by Matthias
Johan's answer is correct, just for the sake of completeness: An alternative way to check the 'bar' elements with rest-assured would be
约翰的回答是正确的,只是为了完整起见:另一种使用放心检查“条”元素的方法是
expect().
body("[0].bar", equalTo(2)).
body("[1].bar", equalTo(4));

