...
Camel supports JSonPath to allow using Expression or Predicate on json messages.
Code Block |
---|
from("queue:books.new")
.choice()
.when().jsonpath("$.store.book[?(@.price < 10)]")
.to("jms:queue:book.cheap")
.when().jsonpath("$.store.book[?(@.price < 30)]")
.to("jms:queue:book.average")
.otherwise()
.to("jms:queue:book.expensive")
|
...
If you prefer to configure your routes in your Spring XML file then you can use JSonPath expressions as follows
Code Block | ||
---|---|---|
| ||
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start"/>
<choice>
<when>
<jsonpath>$.store.book[?(@.price < 10)]</jsonpath>
<to uri="mock:cheap"/>
</when>
<when>
<jsonpath>$.store.book[?(@.price < 30)]</jsonpath>
<to uri="mock:average"/>
</when>
<otherwise>
<to uri="mock:expensive"/>
</otherwise>
</choice>
</route>
</camelContext>
|
...
See the JSonPath project page for further examples.
Suppress exceptions
Available as of Camel 2.16
By default jsonpath will throw an exception if the json payload does not have a valid path accordingly to the configured jsonpath expression. In some use-cases you may want to ignore this in case the json payload contains optional data. Therefore you can set the option suppressExceptions to true to ignore this as shown:
Code Block |
---|
from("direct:start")
.choice()
// use true to suppress exceptions
.when().jsonpath("person.middlename", true)
.to("mock:middle")
.otherwise()
.to("mock:other"); |
And in XML DSL:
Code Block | ||||
---|---|---|---|---|
| ||||
<route>
<from uri="direct:start"/>
<choice>
<when>
<jsonpath suppressExceptions="true">person.middlename</jsonpath>
<to uri="mock:middle"/>
</when>
<otherwise>
<to uri="mock:other"/>
</otherwise>
</choice>
</route>
|
This option is also available on the @JsonPath
annotation.
JSonPath injection
You can use Bean Integration to invoke a method on a bean and use various languages such as JSonPath to extract a value from the message and bind it to a method parameter.
For example
Code Block |
---|
public class Foo {
@Consume(uri = "activemq:queue:books.new")
public void doSomething(@JsonPath("$.store.book[*].author") String author, @Body String json) {
// process the inbound message here
}
}
|
...
If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).
Code Block | ||||
---|---|---|---|---|
| ||||
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jsonpath</artifactId>
<version>x.x.x</version>
</dependency>
|