我有一个 Java 应用程序可以获取像这样的 JSON 字符串
{
"name": "testName",
"message": [
"TestMessage."
]
}
我需要检查是否有值为“TestMessage”的“消息”数组节点。在它的任何元素中。
我可以在我的代码中访问 com.jway.jsonpath.JsonPath。但看起来它只能读取特定节点的值。例如。像这样我将能够获取“消息”数组的第一个元素
JsonPath.read(content, "$.message[0]")
但在这种方式下,我必须将数组的所有元素提取到 Java 中并在那里验证它们。 相反,我想通过 JsonPath 引擎本身执行此检查。
如何使用 JsonPath 实现此目标?使用其他库是否更好?
最佳答案
您可以使用过滤操作。
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")]).
像这样:
JsonPath.read(json, "$.message[?(@ == "TestMessage.")]");
更多可以引用https://github.com/json-path/JsonPath的readme.MD
关于java - 检查 JSON 是否包含具有值的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660886/