检查 JSON 是否包含具有值的节点
Check if JSON containts node with value
我有 Java 个应用程序可以得到 JSON 个像这样的字符串
{
"name": "testName",
"message": [
"TestMessage."
]
}
我需要检查是否有一个 "message" 数组节点在其任何元素中的值为 "TestMessage."。
我可以在我的代码中访问 com.jway.jsonpath.JsonPath。但看起来它只能读取特定节点的值。例如。像这样我将能够获取 "message" array
的第一个元素
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/JsonPathreadme.MD
我有 Java 个应用程序可以得到 JSON 个像这样的字符串
{
"name": "testName",
"message": [
"TestMessage."
]
}
我需要检查是否有一个 "message" 数组节点在其任何元素中的值为 "TestMessage."。
我可以在我的代码中访问 com.jway.jsonpath.JsonPath。但看起来它只能读取特定节点的值。例如。像这样我将能够获取 "message" array
的第一个元素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/JsonPathreadme.MD