Thursday, October 17, 2013

Taste of Apache Camel: Part V - Marshalling and Unmarshalling

In previous post we stored data to Apache Solr from text file written in special format. To parse this file, special parsing method was created. But we could avoid this method just by having data in some standard format like XML, JSON or CSV and use unmarshalling. I will show here how this is done with XML and JSON file formats.


To do JAXB unmarshalling with Camel, new dependency must be added in pom.xml, camel-jaxb.
Next, file movies.txt from Post III must be changed. I will name it movies.xml and of course put in some tags:

For XML unmarshalling we must add JAXB annotations to our Movie POJO.

I surrounded it with Movies POJO for easier unmarshalling.

And now we will make a new route in configure() method in our route builder class.

First there must be defined JaxbDataFormat for route to know how to map XML to Object.
Route starts with loading movies.xml file and does unmarshalling with simple command and moviesData JaxbDataFormat.
Then processor sets route body from Movies to List so splitter would take whole body and we don't have to make new splitter method. And that is all there is to it.

Instead of unmarshalling whole XML, it can be done for every movie separately.

Defined JaxbDataFormat is now for Movie object.
Here file is loaded as before, but unmarshalling is done inside splitter which at first splits XML on movie tags.


Because unmarshalling JSON in Camel does not need JAXB annotation, different dependency must be added in pom.xml, camel-jackson.
Next, we will change file movies.xml into JSON format and name it movies.js:

The first route that unmarshalls XML will be changed just minimal.

As you can see, after unmarshall method, route calls json method where we specify how this JSON will be unmarshalled. Everything else is the same as in previous example. There is no need of JaxbDataFormat because here unmarshalling is done with POJO field and method names that must be the same as in JSON.


If you were converting XML into JSON by hand, marshalling can help you very easy and fast.

As you can see, first XML file gets unmarshalled and after that marshalling is done same way as unmarshalling of JSON. The String is then written into file movies2.js. Marshalling can be done with String as with InputStream.

My posts on Apache Camel:
 - Part I - Property Placeholder
 - Part II - Using Beans
 - Part III - More on using Beans
 - Part IV - Solr
 - Part V - Marshalling and Unmarshalling

No comments:

Post a Comment