Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: CAMEL-5135

...

By default Camel uses the XStream library.

Using

...

Json data format with the XStream library

Code Block
// lets turn Object messages into json then send to MQSeries
from("activemq:My.Queue").
  marshal().json().
  to("mqseries:Another.Queue");

...

Code Block
xml
xml
       <route>
            <from uri="direct:back"/>
            <unmarshal ref="jack"/>
            <to uri="mock:reverse"/>
        </route>

Excluding POJO fields from marshalling

When marshalling a POJO to JSON you might want to exclude certain fields from the JSON output. With Jackson you can use JSON views to accomplish this. First create one or more marker classes.

Wiki Markup
{snippet:id=marker|lang=java|url=camel/trunk/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/Views.java}

Use the marker classes with the @JsonView annotation to include/exclude certain fields. The annotation also works on getters.

Wiki Markup
{snippet:id=jsonview|lang=java|url=camel/trunk/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/TestPojoView.java}

Finally use the Camel JacksonDataFormat to marshall the above POJO to JSON.

Wiki Markup
{snippet:id=format|lang=java|url=camel/trunk/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonMarshalViewTest.java}

Note that the weight field in missing in the resulting JSON:

Code Block

{"age":30, "height":190}

The GSON library supports a similar feature through the notion of ExclusionStrategies:

Wiki Markup
{snippet:id=strategy|lang=java|url=camel/trunk/components/camel-gson/src/test/java/org/apache/camel/component/gson/GsonMarshalExclusionTest.java}

The GsonDataFormat accepts an ExclusionStrategy in its constructor:

Wiki Markup
{snippet:id=format|lang=java|url=camel/trunk/components/camel-gson/src/test/java/org/apache/camel/component/gson/GsonMarshalExclusionTest.java}

The line above will exclude fields annotated with @ExcludeAge during JSON marshalling.

Dependencies for XStream

To use JSON in your camel routes you need to add the a dependency on camel-xstream which implements this data format.

...