Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
642 views
Welcome To Ask or Share your Answers For Others

1 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> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...