You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSONPath中Option.DEFAULT_PATH_LEAF_TO_NULL配置不生效问题求助

问题解决:JSONPath访问不存在字段仍抛PathNotFoundException

问题根源

JSONPath的默认配置包含REQUIRE_PROPERTIES选项,该选项会强制要求路径中的所有属性必须存在,否则抛出PathNotFoundException。这个默认选项的优先级会覆盖你添加的DEFAULT_PATH_LEAF_TO_NULL和SUPPRESS_EXCEPTIONS,导致你期望返回null的场景依然报错。

解决方法

修改配置,移除默认的REQUIRE_PROPERTIES选项,再添加所需的两个选项即可:

方式1:基于默认配置修改

private static final Configuration suppressExceptionConfiguration = Configuration
        .defaultConfiguration()
        .removeOptions(Option.REQUIRE_PROPERTIES)
        .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS);

方式2:使用Builder模式创建全新配置

private static final Configuration suppressExceptionConfiguration = Configuration.builder()
        .options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS)
        .build();

验证效果

修改配置后,执行原访问代码:

DocumentContext jsonContext = JsonPath.using(suppressExceptionConfiguration).parse(json);
String name = jsonContext.read("$.abc.name");

此时name会被赋值为null,不再抛出PathNotFoundException。

内容的提问来源于stack exchange,提问作者SRJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:38:14