问题
I've been searching for the best way to perform the following action using JaxB but I cannot find a way that works. I followed the tutorial here to allow for marshaling and unmarshaling of subclasses.
It achieves all that I am looking for, except that in order for the subclasses to be properly marshaled and unmarshaled, they must be wrapped in a class with a specific @XmlRootElement
. This doesn't allow you to represent the classes themselves as Xml on their own.
I want to have a classes like so:
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlJavaTypeAdapter(ContactMethodAdapter.class)
public abstract class ContactMethod {
}
public class Address extends ContactMethod {
protected String street;
protected String city;
}
public class PhoneNumber extends ContactMethod {
protected String number;
}
and I want to be able to perform the following:
Input:
<contact-method>
<street>Broadway</street>
<city>Seattle</city>
</contact-method>
Main:
public class Demo {
public static void main(String[] args) throws Exception {
ContactMethod meth = (ContactMethod ) unmarshaller.unmarshal(xml);
if(ContactMethod instanceof Address){
Address addr = (Address) meth;
addr.getStreet();
// etc.
}
Address marshalAddr = new Address("Broadway", "Seattle");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal((ContactMethod) marshalAddr, System.out);
}
}
Output:
<contact-method>
<street>Broadway</street>
<city>Seattle</city>
</contact-method>
does anyone know how this can be accomplished?
回答1:
I ended up using one class (AdaptedContactMethod) to model the abstract class. Then I handled the marshaling and unmarshalling to the different subclasses on my own rather than through an @XmlJavaTypeAdapter
.
This allows you to put @XmlRootElement
on your AdaptedContactMethod implementation without having to wrap it in a list.
来源:https://stackoverflow.com/questions/21612210/jaxb-inheritance-marshalling-abstract-classes