我正在制作一个应用程序,它将包含 XML 文件中的数据。
我现在遇到一个问题:JAXB 不编码我的子类,因此当我编码 XML 文件时,所有对象都是父类的对象。
我尝试了 @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);
}
}
重要.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% 包含不同类型的类(class):父级和子级
有什么想法吗?
最佳答案
@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>
关于java - JAXB继承+XMLAdapter(HashMap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371780/