JAX-RS - JSON without root node in apache CXF

If we return the collection object in a REST response, then JSON (it will have the root element node as the name of the collection object - 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" }] 

}

Below is a snippet for our JsonProvider configuration in the 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 do not need the root element of the Collection node in the JSON response. The result should be in the following format. I use the Apache CXF framework for leisure services.

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

}

We use the default cxf JsonProvider (Jettison)

Please suggest any solution. Thanks in advance.

+1
source share
1 answer

You can configure using the droproot element property by setting provider

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

You can also customize using custom JAXBElement, please 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> 
+3
source

Source: https://habr.com/ru/post/1382472/


All Articles