2012-03-03 58 views
2

我正在使用他們的REST API爲Bing翻譯製作一個Java客戶端。我可以使用OAuth進行身份驗證,並且毫無問題地運行翻譯,將這些簡單的字符串響應解組到JAXB對象中,沒有任何問題。但是,當涉及到更復雜的類型時,我正在努力研究爲什麼我總是在Java對象的字段上獲得空值。我從服務中得到的迴應是:從Bing翻譯Java解開REST響應

<ArrayOfstring 
    xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <string>ar</string> 
    <string>bg</string> 
    <string>ca</string> 
    <string>zh-CHS</string> 
    <string>zh-CHT</string> 
</ArrayOfstring> 

我用下面的方法解組對象:

@SuppressWarnings("unchecked") 
    public static <T extends Object> T unmarshallObject(Class<T> clazz, InputStream stream) 
    { 
    T returnType = null; 

    try 
    { 
     JAXBContext jc = JAXBContext.newInstance(clazz); 
     Unmarshaller u = jc.createUnmarshaller(); 

     returnType = (T) u.unmarshal(stream); 
    } catch (Exception e1) 
    { 
     e1.printStackTrace(); 
    } 

    return returnType; 

    } 

工作正常進行簡單的對象,所以我懷疑問題出我的註釋中對於我試圖生成的複雜對象。該代碼是:

package some.package; 
import java.io.Serializable; 
import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAnyElement; 
import javax.xml.bind.annotation.XmlAttribute; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlElementWrapper; 
import javax.xml.bind.annotation.XmlElements; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 
import javax.xml.bind.annotation.XmlValue; 

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name="ArrayOfstring", namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays") 
public class ArrayOfString implements Serializable 
{ 

    @XmlElement(name="string", namespace="http://schemas.microsoft.com/2003/10/Serialization") 
    private List<String> string; 

    public List<String> getString() 
    { 
    return string; 
    } 

    public void setString(List<String> strings) 
    { 
    this.string = strings; 
    } 

} 

無奈之下,我@XmlAnyElement取代@XmlElement(名稱=「字符串」),我得到字符串列表回來,但沒有值。

所以,我的問題是 - 需要改變上述XML的正確解釋,更重要的是爲什麼?

回答

1

在您的示例中,您的string元素實際上屬於http://schemas.microsoft.com/2003/10/Serialization/Arrays名稱空間。

您的註釋表示您期望http://schemas.microsoft.com/2003/10/Serialization命名空間。

嘗試

@XmlElement(name="string", 
    namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays") 
private List<String> string; 

代替。

+0

這工作出色。我的工作假設是'string'是一個位於_http://schemas.microsoft.com/2003/10/Serialization_名稱空間下的對象,那麼它必須是用於數組中元素的相同名稱空間。我錯了。謝謝! – Benemon 2012-03-04 10:27:04