jaywayjsonpath在读取不存在的json路径时抛出错误,尽管已配置为

hwazgwia  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(591)

我有一些json是这样的:

  1. {
  2. "root": {
  3. "metadata": {
  4. "name": "Farmer John",
  5. "hasTractor": false
  6. },
  7. "plants": {
  8. "corn": 137.137,
  9. "soy": 0.45
  10. },
  11. "animals": {
  12. "cow": 4,
  13. "sheep": 12,
  14. "pig": 1
  15. },
  16. "family": {
  17. "isMarried": true
  18. }
  19. }
  20. }

我正在使用 JsonPath :

  1. val document = Configuration.defaultConfiguration()
  2. .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
  3. .jsonProvider()
  4. .parse(jsonString): Object
  5. val value = JsonPath.read(document, "$.root.family.hasChild"): Any

但我得到了一个错误:

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

我应该得到 null 因为我有配置选项 Option.DEFAULT_PATH_LEAF_TO_NULL 在文档创建代码中设置对吗?但是我却得到了这个错误
编辑:
我只需捕获错误并返回null,就可以让它正常工作,如下所示:

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

然而,我仍然在寻找如何做它的“正确”的方式

iih3973s

iih3973s1#

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

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

这是否比捕获异常更高效,可能取决于实现。如果你选择 DEFAULT_PATH_LEAF_TO_NULL 然后简单地遇到一个不存在的叶子 null 否则,将引发异常。在处理数量较少的案件时,这种差异可能并不明显,但如果这种情况经常发生,事情可能会累加起来。

相关问题