jayway jsonpath 在读取 json 路径时抛出错误,尽管配置为

jayway jsonpath throwing an error when reading a json path that does not exist despite being configured to

我有一些 json 是这样的:

{
  "root": {
    "metadata": {
      "name": "Farmer John",
      "hasTractor": false
    },
    "plants": {
      "corn": 137.137,
      "soy": 0.45
    },
    "animals": {
      "cow": 4,
      "sheep": 12,
      "pig": 1
    },
    "family": {
      "isMarried": true
    }
  }
}  

我正在使用 JsonPath:

这样解析
val document = Configuration.defaultConfiguration()
        .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
        .jsonProvider()
        .parse(jsonString): Object
val value = JsonPath.read(document, "$.root.family.hasChild"): Any  

但我收到错误消息:

No results for path: $['root']['family']['hasChild']
com.jayway.jsonpath.PathNotFoundException: No results for path: $['root']['family']['hasChild']
    at com.jayway.jsonpath.internal.path.EvaluationContextImpl.getValue(EvaluationContextImpl.java:133)
    at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
    at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102)  

我应该得到 null 因为我在文档创建代码中设置了配置选项 Option.DEFAULT_PATH_LEAF_TO_NULL 对吗?但是我得到了那个错误

编辑:
我能够通过简单地捕获错误并像这样返回 null 来让它工作:

val value = try {
  JsonPath.read(document, "$.root.family.hasChild"): Any
} catch {
  case _: PathNotFoundException => null
}  

但是,我仍在寻找“正确”的方法

使用 JsonPath.parse() 方法像这样尝试:

Configuration configuration = Configuration.builder().options(Option.DEFAULT_PATH_LEAF_TO_NULL).build();
val value = JsonPath.parse(document, configuration).read("$.root.family.hasChild"));

这是否比捕获异常更有效或更不有效 depend on the implementation。查看 Jayway 代码,如果遇到选项 DEFAULT_PATH_LEAF_TO_NULL 和一个不存在的叶子,则只返回 null ,否则会抛出异常。在处理少量案例时,差异可能不明显,但如果这种情况发生很多,事情可能会加起来。