Saturday, October 22, 2011

JAX-RS with Jersey

When I started building RESTful services, I didn't think I would need a JAX-RS implementation. Why introduce a framework when I can write few lines of code to achieve the same results. For JSON serialization, I had been using Flexjson and was very happy with it. So happy, I will in fact link to its site to improve its page ranking. (As fas as I can recall, I chose Flexjson over GSON because Flexjson would serialize my getter methods, whereas GSON would serialize the fields. My getter methods were encrypting certain fields, which I wanted to send over the wire, not the raw fields themselves.)

My RESTful services worked wonderful, but making changes was turning out painful. I downloaded Jersey, and refactored my code to use JAX-RS annotations. The code was cleaner, easier to maintain, and easily understood and disciplined. Very importantly, I can now write a small script to generate documentation for my web services. I didn't look back.

One hitch I encountered was with my JSON serialization. Jersey was using Jettison by default and the generated JSON had some weird characteristics. For example, instead of just serializing the object as { object }, it would serialize as: { class : object }. Also, a single item array would be serialized differently than if the array had multiple items.

I do not know if there is a way to correct these problems in Jettison, but i switched to Jackson serializer and everything went smooth from there. Jackson already comes bundled with Jersey. I had to add "org.codehaus.jackson.jaxrs" to the list of packages that Jersey would look for to instrument. Basically in web.xml:
 <servlet>
   <servlet-name>restServlet</servlet-name>
   <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
   <init-param>
     <param-name>com.sun.jersey.config.property.packages</param-name>
     <param-value>my.other.packages;org.codehaus.jackson.jaxrs</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
 </servlet>

No comments:

Post a Comment