Java – JAX-RS – JSON without root node in apache CXF

cxfcxfrsjavajax-rsjson

If we return collection object in the REST response, then the JSON (it will have the root element node as the collections object name – employees in this case) will be in the following format:

 {
"employees": [{
    "id": "1",
    "name": "employee name1",
    "company": "ABC Company"
}, {
    "id": "2",
    "name": "employee name2",
    "company": "XYZ Company"
}]

}

Here is a snipper for our JsonProvider config in application context

 <bean id="jsonProvider" class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
 <property name="dropRootElement" value="true" />
 <property name="serializeAsArray" value="true" />
 <property name="dropCollectionWrapperElement" value="true" />
 </bean>

 @XmlRootElement(name="emps")
 public class EmpList{
  private List<Emp> employees;
  //setter and getter methods
  }
 @XmlRootElement(name="emp")
 public class Emp{
   private int id;
   private Sting name;
   private String company;
   //setter and getter methods
  }

I don't want the Collection object root element node in the JSON response. Output should be in the following format. I am using Apache CXF framework for rest services.

 {
 [{
    "id": "1",
    "name": "employee name1",
    "company": "ABC Company"
}, {
    "id": "2",
    "name": "employee name2",
    "company": "XYZ Company"
}]

}

We are using the default cxf JsonProvider (Jettison)

Please suggest any solution. Thanks in advance.

Best Answer

You can configure using droproot element property by customizing the provider

<jaxrs:providers>
            <bean class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
                <property name="dropRootElement" value="true" />
            </bean>                     
</jaxrs:providers>

You can also configure using custom JAXBElement please check here

Example

<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
  <property name="outDropElements">
    <list>
      <!-- ignore drop and {http://numbers}number elements -->
      <value>{http://numbers}number</value>
      <value>index</value>
    </list>
  </property>
</bean>