How to get rid of namespace when marshaling generic objects with JAXB

为君一笑 提交于 2019-12-13 14:12:59

问题


I use the following code to serialize a class:

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();
}

But when I look at the generaetd XML there is a namespace in there:

<?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>

Is there some way to remove this, or tell JAXB that it should NOT add this? I'm looking at this now the whole morning and tried several things I found via google, but nothing helped.

Now I found this thread here: How to marshal without a namespace? but the problem is that the accepted answer is only partially listed and now I don't know if this would help me. XMLStreamWriter is an interface, and I don't want to implement a whole stream writer just for that. So is there some way to extend the ByteArrayOutputStream without the need of implementing all the other functions, such an XMLWriter would need?


回答1:


In this use case the http://www.w3.org/2001/XMLSchema-instance and http://www.w3.org/2001/XMLSchema namespaces are being brought in because of the xsi:type attribute. The xsi:type attribute is being brought in because your JAXB implementation believes the property type to be Object. The solution is to ensure the properties aren't typed Object.

The XML representation looks like part of the representation for java.util.Map (see: http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html). Is this your use case or do you have another object model?



来源:https://stackoverflow.com/questions/17211287/how-to-get-rid-of-namespace-when-marshaling-generic-objects-with-jaxb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!