2013-06-20 45 views
3

我使用下面的代碼序列化類編組通用對象時擺脫命名空間:如何與JAXB

public String serialize(T oObject) 
{ 
    mMarshaller = getJAXBContext().createMarshaller(); 
    mMarshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); 
    ByteArrayOutputStream strm = getOutputStream(); 
    mMarshaller.marshal(oObject, strm); 
    return strm.toString(); 
} 

但是,當我看generaetd XML書中有一個命名空間:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<mapEntry> 
    <key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"> 
    Key 
    </key> 
    <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"> 
    oValue 
    </value> 
</mapEntry> 

有沒有一些方法可以刪除它,或告訴JAXB它不應該添加這個?我現在整個上午都在看這個,並嘗試了幾個我通過谷歌發現的東西,但沒有任何幫助。

現在我發現這個線程在這裏:How to marshal without a namespace?但問題是,接受的答案只是部分列出,現在我不知道這是否會幫助我。 XMLStreamWriter是一個接口,我不想爲此僅實現整個流式編寫器。那麼有什麼方法可以擴展ByteArrayOutputStream而不需要實現所有其他功能,例如XMLWriter所需要的?

回答

2

在此用例中,http://www.w3.org/2001/XMLSchema-instancehttp://www.w3.org/2001/XMLSchema命名空間因爲xsi:type屬性而被引入。由於您的JAXB實現認爲屬性類型爲Object,因此將引入xsi:type屬性。解決方案是確保屬性不是鍵入Object

XML表示看起來像java.util.Map(參見:http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html)表示的部分。這是你的用例還是你有另一個對象模型?

+0

我有一個類實現'java.util.Map.Entry ',所以我猜這個問題是因爲泛型類型,對吧?那我怎麼用通用對象來做到這一點? – Devolus