Tag Archives: Apache CXF

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 org.codehaus.jackson.map.PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES this way:

ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

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="org.codehaus.jackson.map.PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES" />
    </bean>
    
  3. Declare the Jackson ObjectMapper
  4. <bean id="objMapper" class="org.codehaus.jackson.map.ObjectMapper" />
    
  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" />
    </bean>
    
  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" />
    </bean>
    
  11. Finally use your Provider in your JAXRS Resource
  12. <jaxrs:server address="/resource">
       <jaxrs:serviceBeans>
          <ref bean="resource" />
       </jaxrs:serviceBeans>
       <jaxrs:providers>
          <ref bean="snakeJsonProvider" />
       </jaxrs:providers>
    </jaxrs:server>
    

Enjoy and hope this may help!

Advertisements