简体   繁体   中英

JAX-RS - JSON without root node in apache CXF

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM