Convert string to JAXBElement using Java

Syed picture Syed · Apr 21, 2015 · Viewed 7.1k times · Source

I'm having some issue while converting String object to JAXBElement string object where I need to set this one

This is the target method where I need to set the value

public void setData(JAXBElement<String> value) {
    this.data = ((JAXBElement<String> ) value);
}

For this one, I have written code something like this

 ObjectFactory factory = new ObjectFactory();
    JAXBElement<ApplicationIngestionRequest> jaxbElement =  new JAXBElement(
            new  QName(ApplicationIngestionRequest.class.getSimpleName()), ApplicationIngestionRequest.class, request);

    StringWriter writer = new StringWriter();
    JAXBContext context =  JAXBContext.newInstance(ApplicationIngestionRequest.class);
    context.createMarshaller().marshal(jaxbElement, writer);
    LOG.info("JAXBElement object :\n"+ writer.toString());
    Unmarshaller u = context.createUnmarshaller();
    JAXBElement<ApplicationIngestionRequest> o = (JAXBElement<ApplicationIngestionRequest>) u.unmarshal(new StringReader(writer));

Log gives me following output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ApplicationIngestionRequest><BranchCode></BranchCode><SourceCode>0000005511</SourceCode></ApplicationIngestionRequest>

Now when I try to set into the method as

losRequest.setData(o.toString());

It doesn't allow me to set as its expecting as JAXBElement format. Any ideas would be greatly appreciated.

Answer

Ajil Mohan picture Ajil Mohan · Apr 21, 2015

As per the code snippet [setData(JAXBElement value)] , setData , accept instance of '(JAXBElement'). But here , you are trying to set a string value [losRequest.setData(o.toString())] . Here you have to set an instance of 'JAXBElement' .This could be the issue.