CXF Configuration to produce JSON Snake-Case (underscore-case) formatted data using Jackson JSON library

Snake-Case JSON format

It consists of writing JSON data in Snake Case.

Configure JacksonJsonProvider to produce Snake-Case / underscore-case formatted data

JacksonJsonProvider from the jackson-jaxrs library (maven) is configured to produce Camel Case JSON formatted data. In order to produce JSON Snake Case formatted data, you have to set the mapping strategy of the JSON ObjectMapper to this way:

ObjectMapper mapper = new ObjectMapper();

Configure a JSON Snake Case Provider in Apache CXF

In order to configure the JacksonJsonProvider (Message Body Writer and Reader) into CXF using Spring based configuration, proceed this way:

  1. Retrieve the (static) Snake/Underscore strategy
  2. <bean id="snakeStrategy" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
       <property name="staticField" value="" />
  3. Declare the Jackson ObjectMapper
  4. <bean id="objMapper" class="" />
  5. Set the Strategy to the ObjectMapper
  6. <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
       <property name="targetObject" ref="objMapper" />
       <property name="targetMethod" value="setPropertyNamingStrategy" />
       <property name="arguments" ref="snakeStrategy" />
  7. Declare the JaksonJsonProvider
  8. <bean id="snakeJsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
  9. Set the ObjectMapper to the Jackson Provider
  10. <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
       <property name="targetObject" ref="snakeJsonProvider" />
       <property name="targetMethod" value="setMapper" />
       <property name="arguments" ref="objMapper" />
  11. Finally use your Provider in your JAXRS Resource
  12. <jaxrs:server address="/resource">
          <ref bean="resource" />
          <ref bean="snakeJsonProvider" />

Enjoy and hope this may help!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s