简体   繁体   English

JAX-RS - 在apache CXF中没有根节点的JSON

[英]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: 如果我们在REST响应中返回集合对象,那么JSON(它将根元素节点作为集合对象名称 - 在这种情况下是雇员)将采用以下格式:

 {
"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 这是我们在应用程序上下文中的JsonProvider配置的一个剪切器

 <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. 我不希望JSON响应中的Collection对象根元素节点。 Output should be in the following format. 输出应采用以下格式。 I am using Apache CXF framework for rest services. 我正在使用Apache CXF框架进行休息服务。

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

} }

We are using the default cxf JsonProvider (Jettison) 我们使用默认的cxf JsonProvider(Jettison)

Please suggest any solution. 请建议任何解决方案。 Thanks in advance. 提前致谢。

You can configure using droproot element property by customizing the provider 您可以通过自定义provider来使用droproot element属性进行配置

<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 您也可以使用自定义JAXBElement进行配置,请在此处查看

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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