0

I am parsing an json and verify array length like below

from("direct:parseJson")
        .setHeader("numberOfBooks").jsonpath("$..books.length()", int.class)
        .choice()
                .when( simple("${header.numberOfBooks} == '1'"))
                         .log("One book")
                 .otherwise()
                         .log("multiple");

Above Code works, but i am looking for option if we can avoid line 2 with below

 .when( simple("${jsonpath(' $..books.length() ', int.class)} == 1") )

its throwing error

Caused by:
org.apache.camel.language.simple.types.SimpleIllegalSyntaxException:
Unknown function: jsonpath(' $..books.length() ', int.class) == 1 at
location 0
${jsonpath(' $..books.length() ', int.class)} == 1

second try i set header with constant to verify simple expression works or not

.when().jsonpath("$..books.length() > ${header.numberOfBooks}")

Caused by: com.jayway.jsonpath.InvalidPathException: Could not parse token starting at position 18
        at com.jayway.jsonpath.internal.path.PathCompiler.fail(PathCompiler.java:616) ~[json-path-2.4.0.jar:2.4.0]
        at com.jayway.jsonpath.internal.path.PathCompiler.readNextToken(PathCompiler.java:152) ~[json-path-2.4.0.jar:2.4.0]
ImranRazaKhan
  • 1,955
  • 5
  • 33
  • 74

1 Answers1

1

You can use jsonPath directly in your when clause, as described at the camel documentation. Your code would look like this:

from("direct:parseJson")
        .choice()
        .when().jsonpath("$..books.length() == '1'")
                 .log("One book")
             .otherwise()
                 .log("multiple");
Daniel
  • 3,541
  • 3
  • 33
  • 46
  • Its now allowed, I am getting error "The method jsonpath(String) is undefined for the type ChoiceDefinition" – ImranRazaKhan Sep 18 '19 at 08:04
  • @ImranRazaKhan which camel version are you running? – Daniel Sep 18 '19 at 08:05
  • I am using 2.24.1, i go through document and couldn't find where they mentioned we can use jsonpath in choice, All examples contain when() – ImranRazaKhan Sep 18 '19 at 08:10
  • Oh, for Sure. I missed the `when()` in my example. I'll update it – Daniel Sep 18 '19 at 08:13
  • but with 'when' its not working Caused by: org.apache.camel.ExpressionIllegalSyntaxException: Illegal syntax: $..books.length() == '1' Caused by: com.jayway.jsonpath.InvalidPathException: Could not parse token starting at position 18 – ImranRazaKhan Sep 18 '19 at 08:15