Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB Marshalling Objects with java.lang.Object field

Tags:

java

jaxb

I'm trying to marshal an object that has an Object as one of its fields.

@XmlRootElement
public class TaskInstance implements Serializable {
   ...
   private Object dataObject;
   ...
}

The dataObject can be one of many different unknown types, so specifying each somewhere is not only impractical but impossible. When I try to marshal the object, it says the class is not known to the context.

MockProcessData mpd = new MockProcessData();
TaskInstance ti = new TaskInstance();
ti.setDataObject(mpd);

String ti_m = JAXBMarshall.marshall(ti);

"MockProcessData nor any of its super class is known to this context." is what I get.

Is there any way around this error?

like image 936
jcovert Avatar asked Feb 15 '10 22:02

jcovert


People also ask

How does JAXB marshalling work?

In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.

What is Java Marshaller?

The Marshaller class is responsible for governing the process of serializing Java content trees back into XML data.

Which Java classes do we use to Unmarshall information from a file and into in memory objects?

JAXB. JAXB or Java Architecture for XML Binding is the most common framework used by developers to marshal and unmarshal Java objects.


1 Answers

JAXB cannot marshal any old object, since it doesn't know how. For example, it wouldn't know what element name to use.

If you need to handle this sort of wildcard, the only solution is to wrap the objects in a JAXBElement object, which contains enough information for JAXB to marshal to XML.

Try something like:

QName elementName = new QName(...); // supply element name here
JAXBElement jaxbElement = new JAXBElement(elementName, mpd.getClass(), mpd);
ti.setDataObject(jaxbElement);
like image 138
skaffman Avatar answered Oct 07 '22 16:10

skaffman