![](/img/trans.png)
[英]JAXB XMLAdapter: Is there a way to convert this method into JAXB XmlAdapter
[英]JAXB Inheritance + XMLAdapter (HasMap)
我正在制作一個應用程序,它將包含XML文件中的數據。
我現在遇到一個問題:JAXB不會編組我的子類,因此當我umarshall XML文件時,所有對象都是Parent類的對象。 我嘗試了@XMLSeeAlso
, AccessType.FIELD
和JAXBContext jaxbContext = JAXBContext.newInstance(Important.class, Parent.class, Child.class);
一些變體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,其中不包含有關child的任何信息。
<important>
<hashMap>
<entry>
<key>0</key>
<value>
<parentField>1</parentField>
</value>
</entry>
<entry>
<key>0</key>
<value>
<parentField>2</parentField>
</value>
</entry>
</hashMap>
然后關閉標簽。
我的地圖100%包含不同類型的類別:父級和子級
有什么想法嗎?
@XmlSeeAlso
批注使JAXBContext知道您的子類。
將@XmlSeeAlso(Child.class)
添加到您的Parent
類應該可以解決問題。
作為參考,另請參見使用JAXB將子類實例作為超類傳遞的公認答案。
擬議的解決方案
@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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.