我有Java应用程序,它获取像这样的JSON字符串
{
"name": "testName",
"message": [
"TestMessage."
]
}
我需要检查是否存在值为“TestMessage”的“message”数组节点。在任何一个元素中。
我可以在我的代码中访问com.jway.jsonpath.JsonPath。但它看起来只能读取特定节点的值。例如。像这样我将能够获取“消息”数组的第一个元素
JsonPath.read(content, "$.message[0]")
但是通过这种方式,我必须将数组的所有元素都提取到Java中并在那里验证它们。 相反,我想通过JsonPath引擎本身执行此检查。
如何使用JsonPath实现此目标?使用其他库是否更好?
答案 0 :(得分:2)
You can use the filter operations.
Filters are logical expressions used to filter arrays. A typical filter would be [?(@.age > 18)] where @ represents the current item being processed. More complex filters can be created with logical operators && and ||. String literals must be enclosed by single or double quotes ([?(@.color == 'blue')] or [?(@.color == "blue")]).
like this:
JsonPath.read(json, "$.message[?(@ == "TestMessage.")]");
more can refer the readme.MD of https://github.com/json-path/JsonPath