Saturday, January 1, 2011

Using Camel with Jackson JSON Serialization

I previously used Camel-XMPP with Xstream/Jettison JSON Provider to serialize BeanInvocation messages.

It's also possible to use Jackson JSON Provider, with the right configuration.

Add the camel-jackson dependency :

dependencies {
    compile 'org.slf4j:slf4j-api:1.6.1'
    runtime 'org.slf4j:jcl-over-slf4j:1.6.1'
    runtime 'ch.qos.logback:logback-classic:0.9.26'
    compile 'org.apache.camel:camel-core:2.5.0'
    runtime 'org.apache.camel:camel-xmpp:2.5.0'
    runtime 'org.apache.camel:camel-jackson:2.5.0'
}

Configure Camel and Jackson as follows :

camelContext.addRoutes(new RouteBuilder() {
    @Override
    public void configure() throws Exception {
        JacksonDataFormat jacksonDataFormat = new JacksonDataFormat();
        jacksonDataFormat.getObjectMapper().configure(
            SerializationConfig.Feature.INDENT_OUTPUT, true);

        jacksonDataFormat.getObjectMapper()
            .enableDefaultTyping(DefaultTyping.NON_FINAL);

        from("direct:invoice").threads().marshal(jacksonDataFormat).to(xmppUri);
        from(xmppUri).threads().choice()
          .when(body().startsWith("{")).unmarshal(jacksonDataFormat).bean(loggerInvoiceListener)
          .otherwise().to("log:xmpp");
    }
});

The important thing here is defining the Jackson Data Format then enabling default typing for non-final classes.

Now serializing BeanInvocation over Camel XMPP or any transport mechanism (with Jackson) should just work. :-)

No comments:

Post a Comment