【发布时间】:2016-02-10 21:02:18
【问题描述】:
我正在努力使用 JAXB 从我的类/子类中保存所有数据。
我想保存 observableList 中的所有帐户,但问题是,帐户类
public class Account{
private ObjectProperty<HosterObject> host;
....
}
包含一个具有 2 个属性的 HosterObject:
publicName 和 privateName 也有 getter 和 setter。
@XmlRootElement(name = "hoster")
public class HosterObject {
private final StringProperty publicName;
private final StringProperty privateName;
public HosterObject(String publicName, String privateName){
this.publicName = new SimpleStringProperty(publicName);
this.privateName = new SimpleStringProperty(privateName);
}
@XmlElement(name = "publicName")
public StringProperty publicNameProperty(){
return publicName;
}
@XmlElement(name = "privateName")
public StringProperty privateNameProperty(){
return privateName;
}
如何将 Hosterobject 中的内容也保存为 xml 文件中的元素? 目前 xml 文件看起来是这样的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<accounts>
<account>
<hoster/>
<password>123</password>
<status>unchecked</status>
<username>test</username>
</account>
</accounts>
但我应该看起来像这样
...
<account>
<hoster>
<publicName>Name</publicName>
<privateName>private Name</privateName>
</hoster>
....
</account>
....
保存代码:
public void saveAccountDataToFile(File file) {
try {
JAXBContext context = JAXBContext.newInstance(AccountListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our person data.
AccountListWrapper wrapper = new AccountListWrapper();
wrapper.setAccounts(accountData);
// Marshalling and saving XML to the file.
m.marshal(wrapper, file);
} catch (Exception e) {
}
}
包装器:
@XmlRootElement(name = "accounts")
public class AccountListWrapper {
private List<Account> accounts;
@XmlElement(name = "account")
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}
提前致谢!
【问题讨论】:
-
您是否尝试标记 HosterObject 类?如果你想在文件中标记他必须被标记,或者你只是不显示为整个代码。
-
你到底是什么意思?我尝试为对象生成一个自己的包装器并将其传递到这里 JAXBContext.newInstance(AccountListWrapper.class, HosterObjectWrapper.class);但是,我认为,这不是你的意思,或者?
-
您必须通过@XmlRootElement(name = "hoster") 标记HosterObject,并在Account 中标记为HosterObject 设置的@XmlElement 方法。
-
我试过了,但现在抛出异常 com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions org.program.model.HosterObject 没有一个 no- arg 默认构造函数。
-
我不知道我到底改变了什么,但现在它可以工作了。谢谢!