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
相关产品推荐
相关产品推荐

