If there is a way, how to do this, I'd like to know the most elegant one. Here is the question: - Let's assume you have an abstract class Z - You have two classes inherited from Z: named A and B.
You marshal any instance (A or B) like this:
JAXBContext context = JAXBContext.newInstance(Z.class);
Marshaller m = context.createMarshaller();
m.marshal(jaxbObject, ...an outputstream...);
In the resulting XML you see what kind of instance it was (A or B).
Now, how do you unmarshall like
JAXBContext jc = JAXBContext.newInstance(Z.class);
Unmarshaller u = jc.createUnmarshaller();
u.unmarshal(...an inputstream...)
I get an UnmarshalException saying
"Exception Description: A descriptor with default root element {<my namespace>}<the root tag, e.g. A or B> was not found in the project]
javax.xml.bind.UnmarshalException"
So how do you do unmarshalling so that you get an instance of Z and then you can test AFTER unmarshalling, what it is? e.g. z instanceof A then... z instanceof B then something else... etc.
Thanks for any ideas or solutions.
I am using JRE1.6 with MOXy as JAXB Impl.
To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.
Spring BOOT is very smart and it can understand what you need with a little help. To make XML marshalling/unmarshalling work you simply need to add annotations @XmlRootElement to class and @XmlElement to fields without getter and target class will be serialized/deserialized automatically.
To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.
There is a similar question here.
Is it possible, to just unmarshall by providing Person.class
and the unmarshaller finds out itself, whether it has to unmarshall to ReceiverPerson.class
or SenderPerson.class
?
@XmlRootElement(name="person")
public class ReceiverPerson extends Person {
// receiver specific code
}
@XmlRootElement(name="person")
public class SenderPerson extends Person {
// sender specific code (if any)
}
// note: no @XmlRootElement here
public class Person {
// data model + jaxb annotations here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With