我正在制作一个应用程序,它将包含XML文件中的数据。
我现在遇到了一个问题: JAXB不要马歇尔我的子类,所以当我使用umarshall文件时,所有对象都是父类的对象。我尝试了一些@XMLSeeAlso、AccessType.FIELD和JAXBContext jaxbContext = JAXBContext.newInstance(Important.class, Parent.class, Child.class);的变体,但似乎我遇到了一些问题,但它不起作用。
你能给我一些建议吗?我应该使用什么注释?还是mb XMLAdapter?我的项目目前的结构是(我试图简化它):
Main.java
public class Main {
public static void main(String args[]){
JAXB jaxb = new JAXB();
Parent parent = new Parent(1);
Child child = new Child(2,3)
Important important = new Important();
jaxb.write(important);
}
}Important.java
@XmlRootElement(name="important")
public class Important {
public Map<Integer, Parent> hashMap;
//some code here
}Parent.java
public class Parent{
public int parentField;
//constructor
}Child.java
public class Child extends Parent {
public int childField;
//constructors
}简单的JAXB类。JAXB.java
public class JAXB {
public void write(Important important) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Important.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(important, System.out);
} catch (JAXBException e) {
System.err.println(e + "Error.");
}
}
}但是,在编组之后,它返回XML,它不包含任何有关子信息。
<important>
<hashMap>
<entry>
<key>0</key>
<value>
<parentField>1</parentField>
</value>
</entry>
<entry>
<key>0</key>
<value>
<parentField>2</parentField>
</value>
</entry>
</hashMap>
然后关闭标签。
我的map 100%包含不同类型的类:父类和子类
有什么想法吗?
发布于 2015-12-19 15:09:17
@XmlSeeAlso注释让JAXBContext知道您的子类。
将@XmlSeeAlso(Child.class)添加到您的Parent类应该可以做到这一点。
有关参考,请参见Using JAXB to pass subclass instances as superclass的公认答案。
拟议解决方案
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso(Child.class)
public class Parent {
public int parentField;
public Parent(Integer parentField) {
this.parentField = parentField;
}
}结果对我来说
<important>
<map>
<entry>
<key>0</key>
<value>
<parentField>1</parentField>
</value>
</entry>
<entry>
<key>1</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="child">
<parentField>2</parentField>
<childField>3</childField>
</value>
</entry>
</map>
</important>https://stackoverflow.com/questions/34371780
复制相似问题