Apache CXF 2.4.6到2.5.3升级

时间:2015-09-09 10:10:06

标签: java json jackson jax-rs cxf

我尝试将以下代码从Apache CXF 2.4.6更新到Apache CXF 2.5.3:

@Path("/myresource")
public class MyResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Root get() {

        Root root = new Root();
        root.setName("Test");
        return root;
    };
}

@XmlRootElement(namespace = "http://www.my.org", name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Spring配置:

<jaxrs:server address="/myPath" id="myID"
    <jaxrs:serviceBeans>
        <ref bean="myResource" />
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean class="org.apache.cxf.jaxrs.provider.JAXBElementProvider"/>
        <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider" />
    </jaxrs:providers>
</jaxrs:server>

使用Apache CXF 2.4.6和Jackson 2.2.3,我得到了正确的JSON:

{"name":"Test"}

使用Apache CXF 2.5.3和Jackson 2.2.3我得到了错误的JSON:

{"ns1.root":{"name":"Test"}}

客户端:

JAXRSClientFactoryBean jaxrsClientFactoryBean = new JAXRSClientFactoryBean();
jaxrsClientFactoryBean.setAddress(address);
jaxrsClientFactoryBean.setProviders(Arrays.asList(new JacksonJaxbJsonProvider(), new JAXBElementProvider()));
jaxrsClientFactoryBean.setServiceClass(MyResource.class);
MyResource myResource = jaxrsClientFactoryBean.create(MyResource.class);
Root root = myResource.get();

在客户端(代理客户端),我得到一个例外:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"ns1.root"). Expected elements are <{http://www.my.org}root>

我读了migration guide,但没有找到我的问题的答案。

1 个答案:

答案 0 :(得分:1)

因为您将根元素定义为&#34; root&#34;,所以此节点应该显示在序列化的json中。

您可以通过设置json提供程序的属性dropRootName来删除此根元素,如此处所述。

http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-WrappingandUnwrappingJSONsequences