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

