我正在使用apache-cxf作为实现的JAX-RS。我正在使用POST服务,并遇到以下400
错误,将错误的JSON对象编组为Java without
@XMLRootElement。javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Customer")
资源类别:
@POST
@Path("/create")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createCustomer(Customer customer) throws Exception {
------
-------
}
JAXB对象:中没有@XMLRootElement。
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Customer", propOrder = {
"id",
"effectiveDate",
"customerType",
"customerName",
---
})
public class Customer extends ObjectBase implements Serializable
{
}
ApplicationContext:
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="customerResource"/>
</jaxrs:serviceBeans>
</jaxrs:server>
JSON格式
{
"Customer":
{
"Id": null,
"ExternalKey": [
{
"NaturalKey": "NaturalKey0",
"KeyName": "KeyName0",
"SourceSystem": "XYZ"
},
{
"NaturalKey": "NaturalKey1",
"KeyName": "KeyName1",
"SourceSystem": "Sys"
}
],
"MetaData": {
"ObjectVersion": "50",
"ObjectState": "Synchronized",
"CreatedTime": "2006-05-04T18:13:51.0",
"ModifiedBy": "ModifiedBy0",
"ModifiedTime": "2006-05-04T18:13:51.0",
"Verified": "false"
},
"EffectiveDate": "2006-05-04",
"CustomerType": "ABC",
"CustomerName": "CustomerName0",
"CustomerTag": [
{
"Key": "Customer Number",
"Value": "Value0"
},
{
"Key": "Customer EID",
"Value": "Value1"
}
]
}
}
我尝试添加Jettison作为提供程序,但没有运气
最佳答案
我可以通过将JAX-RS提供程序添加为JSONProvider来解决此问题。在JSONProvider中,为JSON指定相应的名称空间。在这种情况下,我使用了空字符串。
<util:map id="jsonNamespaceMap" map-class="java.util.Hashtable">
<entry key="http://www.mycompany.com/abc/xyz/v1" value=""/>
</util:map>
<bean id="jsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider">
<property name="namespaceMap" ref="jsonNamespaceMap"/>
<property name="dropRootElement" value="false"/>
<property name="ignoreMixedContent" value="true"/>
<property name="serializeAsArray" value="true"/>
</bean>
尽管我还没有找到我想到的几个问题的答案-
1.为什么仅在POST请求的情况下需要JSONProvider?对于GET请求,我无需添加JSONProvider即可获取JSON对象作为响应。
2.如果我在客户对象中有@XMLRootElement,我又不需要JSONProvider并且服务有效,为什么?