JAX-RS - 在apache CXF中没有根节点的JSON [英] JAX-RS - JSON without root node in apache CXF

查看:410
本文介绍了JAX-RS - 在apache CXF中没有根节点的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"
}]

}

以下是应用程序上下文中JsonProvider配置的一个解析器

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
  }

我不想要JSON响应中的集合对象根元素节点。输出应采用以下格式。我正在使用Apache CXF框架进行休息服务。

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"
}]

}

我们使用默认的cxf JsonProvider(Jettison)

We are using the default cxf JsonProvider (Jettison)

请提出任何解决方案。在此先感谢。

Please suggest any solution. Thanks in advance.

推荐答案

您可以通过自定义提供程序

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

您还可以使用自定义JAXBElement进行配置,请检查这里

You can also configure using custom JAXBElement please check here

示例

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

这篇关于JAX-RS - 在apache CXF中没有根节点的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆