JaxB继承编组抽象类 [英] JaxB inheritance marshalling abstract classes
问题描述
我一直在寻找使用JaxB执行以下操作的最佳方法,但我找不到一种有效的方法。我按照教程这里进行编组并且解组子类。
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.
它实现了我正在寻找的所有东西,除了为了使子类被正确编组和解组,它们必须被包装在一个类中使用特定的 @XmlRootElement
。这不允许你自己将类本身表示为Xml。
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.
我希望有这样的类:
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:
输入:
<contact-method>
<street>Broadway</street>
<city>Seattle</city>
</contact-method>
主要:
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);
}
}
输出:
<contact-method>
<street>Broadway</street>
<city>Seattle</city>
</contact-method>
有谁知道如何实现这一目标?
does anyone know how this can be accomplished?
推荐答案
我最终使用一个类(AdaptedContactMethod)来为抽象类建模。然后我自己处理marshaling和unmarshalling到不同的子类,而不是通过 @XmlJavaTypeAdapter
。
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
.
这个允许您在AdaptedContactMethod实现上放置 @XmlRootElement
,而不必将其包装在列表中。
This allows you to put @XmlRootElement
on your AdaptedContactMethod implementation without having to wrap it in a list.
这篇关于JaxB继承编组抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!