我正在尝试使用返回XML
的api。
api url:api
这就是我的XML
类的外观:
@XmlRootElement(name="ArrayOfExchangeRatesTable")
@XmlAccessorType(XmlAccessType.FIELD)
public class RootElement {
@XmlElement(name="ExchangeRatesTable")
private TableRateModel tableRateModel;
@XmlAccessorType(XmlAccessType.FIELD)
public class TableRateModel {
@XmlElement(name="Table")
private String table;
@XmlElement(name="EffectiveDate")
private Date effectiveDate;
@XmlElement(name="Rates")
private List<RateModel> rates;
@XmlAccessorType(XmlAccessType.FIELD)
public class RateModel {
@XmlElement(name="Currency")
private Currency currency;
@XmlElement(name="Code")
private String code;
@XmlElement(name="Mid")
private Double mid;
然后最后我打印出来并得到一个结果:
RootElement{tableRateModel=TableRateModel{table='A', effectiveDate=Thu Jul 20 00:00:00 CEST 2017, rates=[RateModel{currency=null, code='null', mid=null}]}}
为什么Rates
列表为空?
答案 0 :(得分:1)
问题是XML元素Rate
包含在名为Rates
的元素中。我测试了以下类并使其工作
@XmlRootElement(name = "ArrayOfExchangeRatesTable")
@XmlAccessorType(XmlAccessType.FIELD)
public class RootElement {
@XmlElement(name = "ExchangeRatesTable")
private TableRateModel tableRateModel;
}
@XmlAccessorType(XmlAccessType.FIELD)
class TableRateModel {
@XmlElement(name = "Table")
private String table;
@XmlElement(name = "EffectiveDate")
private Date effectiveDate;
@XmlElement(name = "Rates")
private Rates rates;
}
@XmlAccessorType(XmlAccessType.FIELD)
class Rates {
@XmlElement(name = "Rate")
private List<Rate> rates;
}
@XmlAccessorType(XmlAccessType.FIELD)
class Rate {
@XmlElement(name = "Currency")
private String currency;
@XmlElement(name = "Code")
private String code;
@XmlElement(name = "Mid")
private Double mid;
}
Currency
显然不可序列化,因为它没有无参数构造函数。一种解决方法是添加一个返回Currency
的getter,从String中解析:
@XmlAccessorType(XmlAccessType.FIELD)
class Rate {
@XmlElement(name = "Currency")
private String currency;
@Xml Element(name = "Code")
private String code;
@XmlElement(name = "Mid")
private Double mid;
public Currency getCurrency() {
return Currency.getInstance(currency);
}
}