我对unmarshaller的问题很小。我们来看看这个方法:
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
这是我的ProductListWrapper:
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
我的XML文件:
public void loadProductDataFromFile (File file) {
try {
JAXBContext context = JAXBContext.newInstance(ProductListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
ProductListWrapper wrapper = (ProductListWrapper) um.unmarshal(file); // this always cause exception
products.clear();
products.addAll(wrapper.getProducts());
setProductFilePath(file);
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Fail!");
alert.setHeaderText("Can't read data!");
alert.setContentText("Can't read data from:\n" + file.getPath() );
alert.showAndWait();
}
}
我从ObservableList中保存的方法(我觉得有效):
@XmlRootElement(name = "products")
public class ProductListWrapper {
private List<Product> products;
@XmlElement(name = "products")
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products=products;
}
}
我的产品类:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<products>
<products>
<amount>124</amount>
<ifConttainsPreservatives>false</ifConttainsPreservatives>
<name>Apple</name>
<type>FRUITS</type>
</products>
</products>
类型是IntegerProperty,ProductType(枚举),StringProperty和BooleanProperty。怎么了?有人可以帮帮我吗?
答案 0 :(得分:0)
有两个问题:
standalone
的值应为yes
,而不是true
。Product
的属性。您需要做一些更改:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<products>
<products>
<amount>124</amount>
<ifConttainsPreservatives>false</ifConttainsPreservatives>
<name>Apple</name>
<type>FRUITS</type>
</products>
</products>
public class Product {
...
public Product() {
// invoke constructor that does assign the properties
this(0, false, null, null);
}
}
请注意,如果未初始化/重新分配此类字段,最好使属性字段最终使编译器抱怨:
private final StringProperty name;
private final IntegerProperty amount;
private ProductType type;
private final BooleanProperty ifConttainsPreservatives;