如何验证JSON中是否存在JSON路径

Vin*_*ran 8 json jsonpath

在给定的json文档中,如何验证json路径是否存在?

我正在使用jayway-jsonpath并拥有以下代码

JsonPath.read(jsonDocument, jsonPath)
Run Code Online (Sandbox Code Playgroud)

上面的代码可能会抛出异常

com.jayway.jsonpath.PathNotFoundException:路径没有结果:$ ['abc']

为了减轻它,我打算在尝试使用JsonPath.read读取它之前验证路径是否存在

作为参考,我经历了以下两个文档,但无法真正得到我想要的.

  1. http://www.baeldung.com/guide-to-jayway-jsonpath
  2. https://github.com/json-path/JsonPath

gil*_*des 6

确实可以捕获异常,就像注释中提到的那样,可能有一种更优雅的方法来检查路径是否存在,而无需在整个代码中编写try catch块。

您可以对jayway-jsonpath使用以下配置选项:

com.jayway.jsonpath.Option.SUPPRESS_EXCEPTIONS
Run Code Online (Sandbox Code Playgroud)

启用此选项后,不会引发任何异常。如果使用read方法,则只要未找到路径,它就会简单地返回null

这是JUnit 5和AssertJ的示例,显示了如何使用此配置选项,避免了仅用于检查json路径是否存在的try / catch块:

@ParameterizedTest
@ArgumentsSource(CustomerProvider.class)
void replaceStructuredPhone(JsonPathReplacementArgument jsonPathReplacementArgument) {
    DocumentContext dc = jsonPathReplacementHelper.replaceStructuredPhone(
            JsonPath.parse(jsonPathReplacementArgument.getCustomerJson(),
                    Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS)),
            "$.cps[5].contactPhoneNumber", jsonPathReplacementArgument.getUnStructuredPhoneNumberType());
    UnStructuredPhoneNumberType unstructRes = dc.read("$.cps[5].contactPhoneNumber.unStructuredPhoneNumber");
    assertThat(unstructRes).isNotNull();
    // this path does not exist, since it should have been deleted.
    Object structRes = dc.read("$.cps[5].contactPhoneNumber.structuredPhoneNumber");
    assertThat(structRes).isNull();
}
Run Code Online (Sandbox Code Playgroud)

  • 但是使用这种方法,如果路径存在但其元素值为 null - 我们也会得到 null,对吧? (2认同)