【发布时间】:2017-06-03 08:18:30
【问题描述】:
我正在使用 com.jayway.jsonpath 2.2.0 来查看属性是否在一系列 JSON 记录中。
这是一个使用 JSON 记录的示例
{
"data":
{
"sampleTime": "2017-06-02T11:47:37.040Z",
"target":
{
"gateway": "TEST1",
"probe": "zeus",
"managedEntity": "zeus",
"type": "",
"sampler": "HARDWARE",
"dataview": "HARDWARE",
"filter":
{
"osType": "Linux",
"pluginName": "HARDWARE"
}
},
"name": "cpuUtilisation",
"row":
{
"Value": "50.39 % (average load)"
}
},
"operation": "update"
}
所以我想匹配 if osType == 'Linux',见上面的记录
我有一些代码尝试这样做,似乎可以工作
@Test
public void test_jsonpath_filter_find_match() throws Exception {
// load in json record from file
String jsonString = FileUtils.readFileToString(new File("resources/geneos-raw.table-cpuutilisation.json"), "UTF-8");
List<Map<String, Object>> match = JsonPath.parse(jsonString).read("$..filter", Filter.filter(Criteria.where("osType").eq("Linux")));
System.out.println("result>" + match);
}
我打印的结果似乎证明 JSON 记录与过滤器匹配
2017/06/03 09:01:27.216 [DEBUG][com.jayway.jsonpath.internal.path.CompiledPath]: Evaluating path: $..['filter']
result>[{"osType":"Linux","pluginName":"HARDWARE"}]
但是,如果我放置一个不匹配的过滤器,我仍然会得到相同的结果。
注意过滤器中的 osType == 'Windows'
@Test
public void test_jsonpath_filter_find_match() throws Exception {
// load in json record from file
String jsonString = FileUtils.readFileToString(new File("resources/geneos-raw.table-cpuutilisation.json"), "UTF-8");
List<Map<String, Object>> match = JsonPath.parse(jsonString).read("$..filter", Filter.filter(Criteria.where("osType").eq("Windows")));
System.out.println("result>" + match);
}
结果是匹配的!
2017/06/03 09:02:06.137 [DEBUG][com.jayway.jsonpath.internal.path.CompiledPath]: Evaluating path: $..['filter']
result>[{"osType":"Linux","pluginName":"HARDWARE"}]
我相信结果应该是一个空的 List 返回。
这是一个错误,还是我的代码/思维有缺陷?
【问题讨论】: