简体   繁体   中英

Unmarshalling XML with JAXB returns NullPointerException

I've made an RESTful api that returns following simple 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>

I'm trying to unmarchall Date and Price but cannot get into nested elements - my code returns NullPointerException on unmarchaller() method. Here's my code

@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;
}
}

Unmarchalling method that returns NullPointerException on System.out.println()

    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;

}

Any hints on this one? I'm really stuck.

Just found solution: private List<GoldRate> goldRateList should be named exactly the same as an element of XML that it refers to, so the proper one is: private List<GoldRate> GoldPrice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM