json - 如何断言json路径值大于值?
问题描述
给定从 REST 调用返回的以下 JSON:
{"Statistik Eintraege":
[{"Wert":"1","Anzahl":41},
{"Wert":"","Anzahl":482},
{"Wert":"-3","Anzahl":1},
{"Wert":"-1","Anzahl":3},
{"Wert":"-2","Anzahl":3}],
"Statistik Typ":"BlahStatistik"}
...我想验证 Wert='' 的'Anzahl' 是否大于 400(在此示例中为:482)。
我在 java 集成测试中尝试的是:
.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", greaterThan(400)));
The exception:
java.lang.ClassCastException: class net.minidev.json.JSONArray cannot be cast to class java.lang.Comparable (net.minidev.json.JSONArray is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at org.hamcrest.comparator.ComparatorMatcherBuilder$1.compare(ComparatorMatcherBuilder.java:22)
at org.hamcrest.comparator.ComparatorMatcherBuilder$ComparatorMatcher.describeMismatchSafely(ComparatorMatcherBuilder.java:86)
at org.hamcrest.TypeSafeMatcher.describeMismatch(TypeSafeMatcher.java:82)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at
我还能尝试什么?
解决方案
JsonPath 运算符[?(<expression>)]
选择与给定表达式匹配的所有元素。因此,结果是一个 json 数组。
在示例[?(@.Wert == '')]
中,将所有 json 节点与Wert
具有空值的字段匹配。您的 json 样本只有一个与谓词匹配的项目,但通常可能有多个。要解决此问题,您必须定义一个仅匹配单个元素的更具体的表达式,或者调整匹配器以处理集合。
配套收藏:
.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", everyItem(greaterThan(400))))
推荐阅读
- amazon-web-services - Kubectl 命令抛出错误:无法连接到服务器:获取凭据:exec:退出状态 2
- javascript - 使用正则表达式格式化输入
- reactjs - 可以根据 id 找到一个对象,然后在反应组件中渲染它
- java - 如何强制@Transactional 工作
? - r - 如何在 R Shiny SelectInput 下拉列表中呈现不等式
- javascript - Td 和 Div 之间的无形边距
- xml - 递归元素的 XML 命名空间定义
- jquery - jQuery:解除绑定transtionend事件
- rust - 我是否需要使用 `let` 绑定来创建更长寿的价值?
- python - 对象tkinter中每个按钮的不同命令?