天天看點

unmarshaller.unmarshal轉換結果是JAXBElement問題問題描述問題解決

unmarshaller.unmarshal轉換結果是JAXBElement問題

  • 問題描述
  • 問題解決
          • 解釋一下:
          • 回去一看

問題描述

根據xml字元串轉換成對象,傳回的類型不是傳入的Class類對象,而是JAXBElement對象。

示例:

public <T> T fromXml(String xml, Class<T> targetClass, String encoding) {
        try {
            JAXBContext jaxbContext = createContext(targetClass);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            XMLStreamReader read = XMLInputFactory.newInstance().createXMLStreamReader(
                    new ByteArrayInputStream(xml.getBytes(encoding)));
            T object = (T) unmarshaller.unmarshal(read);
            return object;  //此時傳回的不是targetClass執行個體,而是JAXBElement對象,JAXBElement對象中的value屬性确是targetClass執行個體
        } catch (Exception e) {
        	...
        }
    }
           

問題解決

https://stackoverflow.com/questions/10243679/when-does-jaxb-unmarshaller-unmarshal-returns-a-jaxbelementmyschemaobject-or-a

  • It depends on the presence of XmlRootElement annotation on the class of your root element.

    If you generate your JAXB classes from an XSD, the following rules are applied:

if the type of the root element is an anonymous type -> XmlRootElement annotation is added to the generated class

if the type of the root element is a top level type -> XmlRootElement annotation is omitted from the generated class

For that reason I often choose anonymous types for root elements.

You can customize the class name of this anonymous type with a customization file. E.g. create a bindings.xjc file like this:

<jxb:bindings version=“1.0”

xmlns:jxb=“http://java.sun.com/xml/ns/jaxb”

xmlns:xs=“http://www.w3.org/2001/XMLSchema”>

<jxb:bindings schemaLocation=“yourXsd.xsd” node="/xs:schema">

<jxb:bindings node="//xs:element[@name=‘yourRootElement’]">

<jxb:class name=“YourRootElementType”/>

</jxb:bindings>

</jxb:bindings>

</jxb:bindings>

解釋一下:

和XmlRootElement 注解有關,如果你的xml的bean類是從xsd生成的,那麼就會出現這些情況:

  • 如果根元素的類型是匿名類型-> XmlRootElement注解将自動添加到生成的類中
  • 如果根元素的類型是頂級類型->生成的類中會省略XmlRootElement注解
回去一看

目前轉化的類的确沒有XmlRootElement注解,加上注解後,問題解決。