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

如何在Apache Camel中编写JsonPath的键存在校验Predicate

解决方案

方案1:使用JsonPathExpressionBuilder构造带异常抑制的Predicate

2.22.x版本中BuilderSupport.jsonpath()没有双参数重载,可直接通过JsonPathExpressionBuilder手动构造符合要求的Predicate:

import org.apache.camel.builder.jsonpath.JsonPathExpressionBuilder;

// 构造单个键存在的Predicate
Predicate scoreExists = JsonPathExpressionBuilder.jsonpath("$.score")
    .suppressExceptions(true)
    .predicate();
Predicate pointsExists = JsonPathExpressionBuilder.jsonpath("$.points")
    .suppressExceptions(true)
    .predicate();

// 路由逻辑
.choice()
    .when(PredicateBuilder.or(scoreExists, pointsExists)).to("direct:b")
    .otherwise().to("direct:c");

注意:使用JsonPathExpressionBuilder需要确保项目已引入camel-jsonpath组件依赖。

方案2:使用原生JSONPath语法简化判断

可以直接在单个JSONPath表达式中完成多键存在判断,无需组合Predicate,也不需要额外配置异常抑制:

.choice()
    // 表达式含义:当前JSON对象存在score或points任意一个属性即匹配
    .when(jsonpath("$[?(@.score || @.points)]")).to("direct:b")
    .otherwise().to("direct:c");

方案3:封装通用工具方法(适合多场景复用)

如果项目中大量需要校验JSON键存在的逻辑,可以封装通用方法减少重复代码:

import org.apache.camel.Predicate;
import org.apache.camel.builder.PredicateBuilder;
import org.apache.camel.builder.jsonpath.JsonPathExpressionBuilder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

private Predicate jsonAnyKeyExists(String... keys) {
    List<Predicate> keyPredicates = Arrays.stream(keys)
        .map(key -> JsonPathExpressionBuilder.jsonpath("$." + key)
            .suppressExceptions(true)
            .predicate())
        .collect(Collectors.toList());
    return PredicateBuilder.or(keyPredicates);
}

// 使用时直接传入需要校验的键即可
.choice()
    .when(jsonAnyKeyExists("score", "points")).to("direct:b")
    .otherwise().to("direct:c");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:51:03