首页 > 解决方案 > 使用 JAXB 解组 XML 返回 NullPointerException

问题描述

我制作了一个 RESTful api,它返回以下简单的 XML:

<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<GoldPriceArray>
  <GoldPrice>
      <Date>2020-06-15</Date>
      <Price>219.01</Price>
  </GoldPrice>
  <GoldPrice>
      <Date>2020-06-16</Date>
      <Price>216.73</Price>
  </GoldPrice>
</GoldPriceArray>

我正在尝试取消日期和价格,但无法进入嵌套元素 - 我的代码在 unmarchaller() 方法上返回 NullPointerException。这是我的代码

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "GoldPriceArray")

public class GoldRates {
private List<GoldRate> goldRateList;
private String goldValue;

public GoldRates() {}

public GoldRates(String goldPrice, List<GoldRate> goldRateList) {
    this.goldRateList = goldRateList;
    this.goldValue = goldPrice;
}

@XmlElement
public List<GoldRate> getList() {
    return goldRateList;
}

public void setList(ArrayList<GoldRate> goldRateList) {
    this.goldRateList = goldRateList;
}

@XmlElement
public String getPrice() {
    return goldValue;
}

public void setPrice(String goldPrice) {
    this.goldValue = goldPrice;}

public class GoldRate {

@XmlElement(name = "Date")
private String dateOfPrice;

@XmlElement(name = "Price")
private String price;

public GoldRate() {
}

public GoldRate(String date, String value) {
    this.dateOfPrice = date;
    this.price = value;
}

public String getDate() {
    return dateOfPrice;
}

public void setDate(String date) {
    this.dateOfPrice = date;
}

public String getValue() {
    return price;
}

public void setValue(String value) {
    this.price = value;
}


@Override
public String toString() {
    return "Date: " + dateOfPrice + " value: " + price;
}
}

在 System.out.println() 上返回 NullPointerException 的 Unmaralling 方法

    public void unmarshaller(String xml) {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(GoldRates.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        GoldRates goldRates = (GoldRates) jaxbUnmarshaller.unmarshal(new StringReader(xml));

        System.out.println(goldRates.getList().get(0).getValue() + " " + goldRates.getList().get(0).getDate());

    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;

}

关于这个有什么提示吗?我真的被困住了。

标签: javaxmljaxb

解决方案


刚刚找到的解决方案: private List<GoldRate> goldRateList 应该与它所引用的 XML 元素的名称完全相同,因此正确的是: private List<GoldRate> GoldPrice


推荐阅读