2014-10-02 6 views
6

quando faccio funzionare l'operazione maresciallo ottengo il seguente errore:Problemi con JAXB, il maresciallo, - in grado di maresciallo tipo “java.lang.String”

javax.xml.bind.MarshalException 
- with linked exception: 
[com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation] 
    ... 

Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation 
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237) 
    at com.sun.xml.internal.bind.v2.runtime.LeafBeanInfoImpl.serializeRoot(LeafBeanInfoImpl.java:126) 
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483) 
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308) 
    ... 6 more 

Questa è la mia funzione di riunire ...

public StringBuffer Marshaller(Object marshall){ // make marshalling->Java to XML 
     StringWriter writer = new StringWriter(); 
     try { 
      JAXBContext jaxbContext=JAXBContext.newInstance(marshall.getClass()); 
      Marshaller jaxbMarshaller=jaxbContext.createMarshaller(); 
      // çıktı 
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
      jaxbMarshaller.marshal(marshall, writer); 
      System.out.println(writer.getBuffer().toString()); 
     } catch (PropertyException e) { 
      e.printStackTrace(); 
     } catch (JAXBException e) { 
      e.printStackTrace(); 
     } 
     return writer.getBuffer(); 

    } 

Grazie per il vostro interesse ..

risposta

9

non si può maresciallo solo un String in quanto non dispone di informazioni elemento radice (da qui l'eccezione circa la mancanzaAnnotazione), ma è possibile racchiuderlo in un'istanza di JAXBElement e quindi eseguirne il marshalling. JAXBElement è un altro modo per fornire le informazioni su questo elemento radice a JAXB.

Esempio di creazione del JAXBElement

JAXBElement<String> jaxbElement = 
    new JAXBElement(new QName("root-element"), 
    String.class, string); 

Se è stato generato il modello da uno schema XML

Se hai creato il tuo modello di oggetti da uno schema XML. E hai un elemento XML di livello superiore che è un tipo di dati come xs:string quindi ci sarà un metodo di convenienza nella classe generata ObjectFactory che ti aiuterà a creare l'istanza JAXBElement.

+0

Potrebbe spiegarci di più? –

+0

@nurdankaraman - Ho aggiunto alcune informazioni aggiuntive alla mia risposta. –

+0

Grazie mille :) –