使用XML返回选定日期以便XMLElements

时间:2017-07-20 17:00:52

标签: java xml jaxb

我正在尝试使用返回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列表为空?

1 个答案:

答案 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);
  }
}