簡體   English   中英

在沒有@XMLRootElement的情況下將JSON對象解組為Java

[英]unmarshalling JSON object to Java without @XMLRootElement

我正在使用apache-cxf作為實現來使用JAX-RS。 我正在使用POST服務並在without @XMLRootElement的without JSON對象解組為400錯誤。

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和服務,為什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM