Wednesday, January 4, 2012

CXF Rest service renders JSON with @ for attributes

In my current project I am exposing lots of Rest Services in Java using CXF. All the service should be able to render response in json and xml format. This can very easily be done by just using a annotation(@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })) on the exposed service method. To verify the service is rendering correct response based on passed header type (accept:application/json or accept:application/xml).

I used JsonView firefox plugin. (I like this plugin since you get formatted JSON back vs one line response which you get if you will use Poster firefox plugin).

I noticed that JSON output has extra '@' symbol for attributes. i.e.

......"Programs": {"Channel": {
"
@ID"
: "E",
"TopName": "The Fresh Prince of Bel-Air",
"
BottomName"
: "Bang the Drum Ashley",
"StartTime": {
"
@utc"
: "1325741400000",
"
$"
: "2012-01-05T05:30:00"
},...........


Then after googling I found that CXF default JSON render is Jettison which produced this sort of output. (Why Jettison behaves in such a way is still mystery. I have to it figure out sooner than later.)

If you will replace the default JSON renderer Jettison with Jackson problem will be resolved and it' very simple to provide your custom Provider. I added following lines into my spring.xml

<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationConfig.dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="EEE, d MMM yyyy HH:mm:ss z" />
</bean>
</property>
</bean>

<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider">
<property name="mapper" ref="jacksonObjectMapper" />
</bean>


and added the provider into my server declaration i.e
<jaxrs:server id="xService" address="/x">
<jaxrs:serviceBeans>
<ref bean="xServices" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
</jaxrs:providers>
</jaxrs:server&g
After adding Jackson as my provider. I redeployed my project and JSON was coming without @ sign. :))))

"programList": [{
"isHD": true,
"isClosedCaptioned": false,
"length": 120,
"description": "",
},
"startTime": {
"textValue": "2012-01-05T17:00:00",
"utcStartTime": 1325782800000 ....

-Enjoy
Manisha

No comments:

Post a Comment