0

In my Apache Camel application I have multiple conditions checking the existence of keys in a JSON. I want to reduce the boiler plate code, therefore I need to transform my Expressions to a Predicate.

My code with Expressions:

.choice()
    .when().jsonpath("$.score", true).to("direct:b")
    .when().jsonpath("$.points", true).to("direct:b")
    .otherwise().to("direct:c");

See also: JSONPATH

My code with Predicates:

.choice()
    .when(PredicateBuilder.or(jsonpath("$.score", true), jsonpath("$.points", true))).to("direct:b")
    .otherwise().to("direct:c");

See also: PREDICATES

But this is not working, because there is no suppressExceptions parameter (see BuilderSupport#jsonpath). Unfortunately, there is also no exists mehod (see ValueBuilder).

How can I write a Predicate for checking the existence of a key in a JSON?

dur
  • 15,689
  • 25
  • 79
  • 125

1 Answers1

0

this code solve your problem .

.choice()
    .when(PredicateBuilder.and(jsonpath("$[?(@.score)]"), jsonpath("$.score"))).to("direct:b")
    .when(PredicateBuilder.and(jsonpath("$[?(@.points)]"), jsonpath("$.points"))).to("direct:b")
    .otherwise().to("direct:c");
dur
  • 15,689
  • 25
  • 79
  • 125
erayerdem
  • 775
  • 6
  • 12
  • Thank you, but now there are two `when`s again. My goal is to use only one `when`, because I do not want to write redundant `to`s (in my case there are some lines of code, not only one `to`). Do you know a solution? Maybe combine both with `PredicateBuilder.or`? – dur Aug 21 '21 at 08:34
  • u can concet predicates like that https://stackoverflow.com/a/9273050/8916556 – erayerdem Aug 21 '21 at 11:04